您的位置:首页 > 其它

Rectangle Area -- leetcode

2015-09-10 17:02 232 查看
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. left 取两个矩形left的最大值。 right取两者right最小值。

2. top和bottom同理。

检查求出的上限是否大于下限,即left是否小于right,bottom是否于小于top。如果不是,则没有重叠部分。

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int ans = (C-A) * (D-B) + (G-E) * (H-F);
        int a = max(A, E);
        int b = max(B, F);
        int c = min(C, G);
        int d = min(D, H);
        if (a >= c || b >= d)
            return ans;
        
        return ans - (c-a) * (d-b);
    }
};


上面代码可以简化一下为:

省去了判断上限是否大于上限。将重叠和不重叠彻底统一处理。

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int a = max(A, E);
        int b = max(B, F);
        int c = max(a, min(C, G));
        int d = max(b, min(D, H));
        
        return (C-A) * (D-B) + (G-E) * (H-F) - (c-a) * (d-b);
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: