Description
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.
Solution
求解两个矩形的并集的面积,可以转换成两个矩形面积之和减去两个矩形交集的面积求解矩形面积为长乘以宽,其中(对于矩形ABCD)长为C-A,宽为D-B,求解矩形交集的矩形面积时,需要获取交集(可能没有交集)的长宽,要求解长宽,需要获取该矩形的四个边界,其中左边界left为两矩形左边界(A,E)的最大值,右边界right为两矩形右边界(C,G)的最小值,上边界top和下边界bottom同理。
Code
public class Solution {
public int computeArea(
int A,
int B,
int C,
int D,
int E,
int F,
int G,
int H) {
int left = Math.max(A, E);
int right = Math.min(C, G);
int top = Math.min(D, H);
int bottom = Math.max(B, F);
int all = (D - B) * (C - A) + (H - F) * (G - E);
if(left < right && bottom < top){
return all - (right - left) * (top - bottom);
}
return all;
}
}