223. 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.
Assume that the total area is never beyond the maximum possible value of int.
两个矩形求和,一共有2种情况:2个矩形独立、2个矩形存在公共区域
公共区域:无论两个矩形如何交叉,都有宽=min(C,G)-max(A,E),高=min(D,H)-max(B,F)
<span style="font-size:18px;">class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int areaA=(C-A)*(D-B);
int areaE=(G-E)*(H-F);
int sum=0; //2个矩形面积和
if(G<=A||E>=C){ //2矩形没有重合
sum=areaA+areaE;
}
else if(D<=F||B>=H)
{
sum=areaA+areaE;
}
else{
int l=min(D,H)-max(B,F);
int w=min(C,G)-max(A,E);
sum=areaA+areaE-l*w;
}
return sum;
}
};</span>