題目來源
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.
求兩個(gè)矩形覆蓋的面積。
假如沒有重疊邪驮,直接算倆矩形面積壕曼。
假如有重疊尤辱,只要兩個(gè)矩形面積扣除重合部分的面積就可以了贬芥。
難點(diǎn)在于如何判斷有沒有重疊。
重疊的情況實(shí)在有點(diǎn)多蜀备,我考慮了半天還是沒考慮好各種情況删咱。
然后看了下情況,有點(diǎn)巧妙…根本想不到…
說不太清楚奶赔,直接看代碼吧惋嚎。
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);
int bottom = max(B, F), top = max(min(D, H), bottom);
int s1 = (C-A) * (D-B) + (G-E) * (H-F);
int s2 = (right - left) * (top - bottom);
return s1 - s2;
}
};