您的位置:首页 > 其它

#leetcode#Rectangle Area

2015-06-16 02:35 267 查看
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.

注意这题是找总面积, 不是只找overlap的面积, 做题的时候思维定式没看题就直接写了。。
首先判断两矩形有无相交,
若不相交, 则返回两矩形面积之和
若相交, 则再减去相交部分的面积
如何计算相交部分的面积?
首先看行的长度, 两矩形右上顶点横坐标的最小值是相交部分的右边界, 左下顶点横坐标的最大值是左边界, 相减得横边长
同理, 两右上顶点竖坐标的最小值是相交部分的上边界, 左下顶点竖坐标的最大值是下边界,相减得竖边长
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int sum = (D - B) * (C - A) + (H - F) * (G - E);
int overlapArea;
if( E >= C || F >= D || A >= G || B >= H)
overlapArea = 0;
else
overlapArea = (Math.min(C, G) - Math.max(A, E)) * (Math.min(D, H) - Math.max(B, F));
return sum - overlapArea;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode