問題
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.
Assume that the total area is never beyond the maximum possible value of int.
例子
-2 -2 2 2 -2 -2 2 2
16
分析
- 方法一:首先判斷兩個矩形是否相交。如果相交,總面積就是兩個矩形的面積和;如果不相交,總面積等于兩個矩形的面積和-重疊部分的面積;
- 方法二:通過min max函數直接求出重疊部分的面積,當矩形不相交時,重疊面積為0。
要點
分情況討論=>歸一化為一種情況
時間復雜度
O(1)
空間復雜度
O(1)
代碼
方法一
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int total = (C - A) * (D - B) + (G - E) * (H - F);
if (C <= E || G <= A || D <= F || H <= B) return total;
vector<int> x{A, C, E, G};
vector<int> y{B, D, F, H};
sort(x.begin(), x.end());
sort(y.begin(), y.end());
int intersection = (x[2] - x[1]) * (y[2] - y[1]);
return total - intersection;
}
};
方法二
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int left = max(A, E), right = max(min(C, G), left); // 當兩矩形不相交時,right = left
int bottom = max(B, F), top = max(min(D, H), bottom); // 當兩矩形不相交時,top = bottom
return (C - A) * (D - B) + (G - E) * (H - F) - (right - left) * (top - bottom);
}
};