LeetCode 223. Rectangle Area

链接:https://leetcode.com/problems/rectangle-area/

思路:显然总覆盖面积等于两矩形面积减去重合部分面积。设两矩阵R1,R2,重合部分某点P(x,y),它必在R1内部,则A <= x <= C,B <= y <= D;必在R2内部,则E <= x <= G,F <= y <= H。综上,max(A, E) <= x <= min(C, G),max(B, F) <= y <= min(D, H),满足这两个条件的点就是重合部分。如果无法满足,即max(A, E) > min(C, G)或max(B,F) > min(D,H),那就没有重合部分。
Obviously the total area covered is equal to the area of two rectangles minus the area of the overlapping part. Let two rectangles be R1, R1, and let the point P inside the overlapping part have coordinates (x, y). P must be inside R1, so A <= x <= C,B <= y <= D. P must be inside R2, so E <= x <= G,F <= y <= H. To sum up, max(A, E) <= x <= min(C, G),max(B, F) <= y <= min(D, H), and the point meeting these two conditions is inside the overlapping part. If max(A, E) > min(C, G) or max(B,F) > min(D,H), there is no overlapping part.

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int s1 = (C-A)*(D-B), s2 = (G-E)*(H-F); // 先不相加,可能会溢出,如输入(0,0)(40000,50000)(0,0)(40000,50000)
        int left = max(A,E), right = min(C,G);
        int bottom = max(B,F), top = min(D,H);
        if(left < right && bottom < top)
            return s1 - (right-left)*(top-bottom) + s2;
        return s1 + s2;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值