leetcode 223-Rectangle Area
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.
思路:需要计算正方形覆盖的面积和,关键在于计算重合区域的面积,采用以下计算方式;
设重合区域的左边为(left, bottom)(right, top)
left = Math.max(A, E);
bottom = Math.max(B, F);
right和top的计算比较复杂,需要考虑两个方形不相交的情况,比如:[(-2,-2)(2,2)],[(3,3)(4,4)],
right = Math.max(Math.min(C, G), left);
top = Math.max(Math.min(D, H), bottom);
代码如下:
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.max(Math.min(C, G), left); int bottom = Math.max(B, F); int top = Math.max(Math.min(D, H), bottom); return (G-E)*(H-F)+(C-A)*(D-B)-(right-left)*(top-bottom); }
posted on 2015-08-01 23:32 linxiong1991 阅读(131) 评论(0) 编辑 收藏 举报