【LeetCode】223. Rectangle Area

计算两个矩形在二维平面总面积及重叠面积
本文详细介绍了如何计算两个矩形在二维平面中的总面积,包括计算方法和特殊情况处理,并通过示例代码展示了实现过程。

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.

Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.

Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.

 

两个矩形分别面积之和减去重叠面积。

记(A,B)(C,D)表示第一个矩形rect1,(E,F)(G,H)表示rect2

一、有4种情况,rect1和rect2完全不重叠

1、rect1整个在rect2右边,即 A >= G

2、rect1整个在rect2左边,即 C <= E

3、rect1整个在rect2上边,即 B >= H

4、rect1整个在rect2下边,即 D <= F

二、计算重叠面积(即长、宽)

1、计算宽

(1)当 A <= E 时,

重叠部分的最左边即rect2的最左边(E)

重叠部分的最右边可能是rect1的最右边(C),也有可能是rect2的最右边(G)

(2)当 A > E 时,

重叠部分的最左边即rect1的最左边(A)

重叠部分的最右边可能是rect1的最右边(C),也有可能是rect2的最右边(G)

2、计算长

(1)当 D <= H 时,

重叠部分的最上边即rect1的最上边(D)

重叠部分的最下边可能是rect1的最下边(B), 也有可能是rect2的最下边(F)

(2)当 D > H 时,

重叠部分的最上边即rect2的最上边(H)

重叠部分的最下边可能是rect1的最下边(B), 也有可能是rect2的最下边(F)

 

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int width;
        int height;
        
        if(A >= G // rect1 is in the right of rect2
        || C <= E // rect1 is in the left of rect2
        || B >= H // rect1 is above rect2
        || D <= F // rect1 is below rect2
        )
        {// no overlap
            width = 0;
            height = 0;
        }
        else
        {// overlap
            if(A <= E)
                width = min(G - E, C - E);
            else
                width = min(C - A, G - A);
                
            if(D <= H)
                height = min(D - B, D - F);
            else
                height = min(H - F, H - B);
        }
        return (C-A)*(D-B)+(G-E)*(H-F)-height*width;
    }
};

转载于:https://www.cnblogs.com/ganganloveu/p/4638084.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值