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.
思路:就是用两个矩形的面积和减去重叠部分的面积。求出重叠部分的面积就好,不难,就不在赘述了。
代码如下(已通过leetcode)
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
//if(A==C || B==D || E==G || F==H) return 0;
int areaA=(C-A)*(D-B);
int areaB=(G-E)*(H-F);
int htop=Math.min(D, H);
int hbot=Math.max(B, F);
int wleft=Math.max(A, E);
int wright=Math.min(C, G);
if(htop>hbot && wright>wleft) return areaA+areaB-(htop-hbot)*(wright-wleft);
else return areaA+areaB;
}