题目如下:
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.
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int right1 = Math.max(E,G);
int left1 = Math.min(E,G);
int right2 = Math.max(A,C);
int left2 = Math.min(A,C);
int top1 = Math.max(H,F);
int bottom1 = Math.min(H,F);
int top2 = Math.max(B,D);
int bottom2 = Math.min(B,D);
int area1 = (right1-left1)*(top1-bottom1);
int area2 = (right2-left2)*(top2-bottom2);
if(right1<=left2 || right2<=left1 || top1<=bottom2 || top2<=bottom1 ){
return area1+area2;
}
int left = Math.max(left1,left2);
int right = Math.min(right1,right2);
int top = Math.min(top1,top2);
int bottom = Math.max(bottom1,bottom2);
return area1+area2-(right-left)*(top-bottom);
}
然后是评论区写的比较好的代码,如下所示,思路一样的,就是人家认真审题了:
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int areaOfSqrA = (C-A) * (D-B);
int areaOfSqrB = (G-E) * (H-F);
int left = Math.max(A, E);
int right = Math.min(G, C);
int bottom = Math.max(F, B);
int top = Math.min(D, H);
//If overlap
int overlap = 0;
if(right > left && top > bottom)
overlap = (right - left) * (top - bottom);
return areaOfSqrA + areaOfSqrB - overlap;
}
最后是评论区有位“patient guy”的代码,这里就不贴了,大家自己感受下什么叫有毅力,标题也非常醒目,我给满分,这个代码的地址在这里:
https://discuss.leetcode.com/topic/17534/if-you-want-to-laugh-look-at-my-solution。
大家以后也要注意审题呦~