LeetCode 223. Rectangle Area

本文介绍了一种计算两个二维矩形重叠面积的方法。首先判断两矩形是否有重叠,若无重叠则总面积为两矩形面积之和;若有重叠,则计算重叠部分的面积并从总面积中减去。文章给出了具体的数学公式和实现代码。



Easy level which probably means easy to make mistakes......

Better to draw a graph to make the question clear..... 


Under these situations, there is no overlap.

Thus, G <= A || E >= C || G <= B || F >= D.... there is no overlap, the total area is the sum of two cubes area 


For the overlap situation, we just need to consider one situation, all the overlaps will be the same anyway....

The easiest one would be one is totally inside the other one.

In this case, the overlap area woud be overlap = abs(min(G, C) - max(A, E)) * abs(max(B,  F) - min(D, H));

Thus the total area is The sum of two cubes area - overlap.....

Generate code would be easy then.....

int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        if(E >= C || G <= A || H <= B || D <= F) return (C-A)*(D-B)+(G-E)*(H-F);
        else {
            return (C-A)*(D-B)+(G-E)*(H-F) - (min(C, G) - max(A, E)) * (min(H, D) - max(B, F));
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值