【题目描述】
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.
分类讨论,寻找规律
【代码】
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int S1=(C-A)*(D-B);
int S2=(G-E)*(H-F);
if(C<=E||G<=A||D<=F||H<=B) return S1+S2;
int m[4],n[4];
m[0]=A;
m[1]=C;
m[2]=E;
m[3]=G;
n[0]=B;
n[1]=D;
n[2]=F;
n[3]=H;
sort(m,m+4);
sort(n,n+4);
int ans=S1+S2-(m[2]-m[1])*(n[2]-n[1]);
return ans;
}
};
改进版本:
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int S1=(C-A)*(D-B);
int S2=(G-E)*(H-F);
if(C<=E||G<=A||D<=F||H<=B) return S1+S2;
int ans=S1+S2-(min(G,C)-max(A,E))*(min(H,D)-max(B,F));
return ans;
}
};