题目描述:
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.
计算两个矩形覆盖的总面积=矩形1面积+矩形2面积-重叠面积。
当F>=D||H<=B||E>=C||G<=A时,重叠区域为0.
代码如下:
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int overlapArea=0;
if(F>=D||H<=B||E>=C||G<=A)
overlapArea=0;
else{
int newA=Integer.max(A, E);
int newB=Integer.max(B, F);
int newC=Integer.min(C, G);
int newD=Integer.min(D, H);
overlapArea=(newC-newA)*(newD-newB);
}
return (C-A)*(D-B)+(G-E)*(H-F)-overlapArea;
}
}