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 class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int res=(C-A)*(D-B)+(G-E)*(H-F);
int A1=Math.max(A,E);
int B1=Math.max(B,F);
int C1=Math.min(C,G);
int D1=Math.min(D,H);
if(A1>=C1 || B1>=D1) return res;
return res-(C1-A1)*(D1-B1);
}
}
运行结果: