【问题描述】
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.
【思路】
先计算两个矩形面积,再判断是否需要减去中间重叠部分面积。
中间矩形(leftx, lefty) (rightx, righty)
int leftx = Math.max(A, E);
int lefty = Math.max(B, F);
int rightx = Math.min(C, G);
int righty = Math.min(D, H);
【code】
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int leftx = Math.max(A, E);
int lefty = Math.max(B, F);
int rightx = Math.min(C, G);
int righty = Math.min(D, H);
int area = (C - A) * (D - B) + (G - E) * (H - F);
if (leftx >= rightx || lefty >= righty) {
return area;
}
return area - (rightx - leftx) * (righty - lefty);
}
}