- Rectangle Area
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
Note:
Assume that the total area is never beyond the maximum possible value of int.
解
计算公式为:S = 矩形1的面积 + 矩形2的面积 - 相交部分的面积
相交的宽 = 矩形1的宽 + 矩形2的宽 - 实际图形的宽
相交的高计算类似
如果相交部分的高或者宽小于0,说明没有相交
题目原本定义的int
会溢出???????
typedef long long int LL;
class Solution {
public:
LL computeArea(LL A, LL B, LL C, LL D, LL E, LL F, LL G, LL H) {
LL S = (C-A)*(D-B) + (G-E)*(H-F);
LL d = abs(C - A) + abs(G - E) - abs(max(G, C) - min(A, E));
LL h = abs(D - B) + abs(H - F) - abs(max(D, H) - min(F, B));
return S - (d > 0 && h > 0 ? d * h : 0);
}
};