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.如果没有重叠,则直接返回两个矩形的总面积:(C-A)*(D-B) + (G-E)*(H-F)。判断两个矩形是否重叠:if(C<E || G<A || H<B || D<F)。
2.如果有重叠,计算重叠面积的大小。总面积-重叠面积。
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int total = (C-A)*(D-B) + (G-E)*(H-F);
if(B>H || C<E || D<F || A>G) return total;
int l = 0;
if(E>A) l = Math.min((C-E),(G-E));
else l = Math.min((C-A),(G-A));
int h = 0;
if(D>H) h = Math.min((H-B),(H-F));
else h = Math.min((D-B),(D-F));
return (total-(l*h));
}
}
计算重叠部分的长和宽是一个难点,要明确可能重叠的几种情况,然后用简洁的代码把它表示出来。