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.
![Rectangle Area](https://leetcode.com/static/images/problemset/rectangle_area.png)
Assume that the total area is never beyond the maximum possible value of int.
思路:先判断两个长方形的相交情况,然后计算相交面积,最后计算总共占用面积
时间复杂度:
代码:
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { return (C-A)*(D-B)+(G-E)*(H-F)-intersectionArea(A, B, C, D, E, F, G, H); } public int intersectionArea(int A, int B, int C, int D, int E, int F, int G, int H) { int situation=intersection(A, B, C, D, E, F, G, H); if(situation==1) return (G-E)*(H-F); else if(situation==2) return (C-A)*(D-B); else if(situation==3) return 0; else return ((Math.min(H, D)-Math.max(B, F))*(Math.min(C, G)-Math.max(A, E))); } /** * 判断相交情况 * 1 ABCD包含EFGH * 2 EFGH包含ABCD * 3 不相交 * 4 相交 * @param A * @param B * @param C * @param D * @param E * @param F * @param G * @param H * @return */ public int intersection(int A, int B, int C, int D, int E, int F, int G, int H) { if(D>=H && C>=G && A<=E && B<=F) return 1; if(G>C && H>D && E<A && F<B) return 2; //如果两长方形的中心点的连线在x轴上的投影小于两长方形x边长度之和的一半, 并且Y也如此,则这两个长方形相交 double x1=(A+C)*1.0/2; double y1=(B+D)*1.0/2; double x2=(E+G)*1.0/2; double y2=(F+H)*1.0/2; double rx=(C-A+G-E)*1.0/2; double ry=(D-B+H-F)*1.0/2; if(Math.abs(x2-x1)<rx && Math.abs(y2-y1)<ry) return 4; else { return 3; } }
优化:
扩展;