Rectangle Area - LeetCode 223

题目描述:
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.

Hide Tags Math

分析:
乍一看,题目比较复杂。两个矩形的位置是任意的,如果不相交,则直接返回两个矩形的和;
如果相交,那么相交的情况有多种,但是最后返回的面积都是两个大矩形的面积减去交叉矩形的面积。
那么重点就是求交叉矩形的面积了。
根据两个大矩形的坐标,是可以得到交叉矩形四个点的坐标的。
其中交叉矩形的较大纵坐标up是两个矩形对应较大纵坐标的较小值
              较小纵坐标down是两个矩形各对应小纵坐标的较大值
              较小横坐标lef是是两个矩形各对应小横坐标的较大值
              较大横坐标rig是是两个矩形各对应大横坐标的较小值

以下是C++实现代码:

/**0ms*/
class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int a = 0, b = 0,c = 0;
        a = (C - A)*(D - B);
        b = (G - E)*(H - F);
        if(C <= E || A  >= G || B >= H ||F >=D ) //不相交
        {
            return a+b;
        }
	//相交,求出交叉矩形的边长
        int up = min(H,D);
        int down = max(B,F);
        int lef = max(A,E);
        int rig = min(G,C);

        c = (up-down) * (rig - lef); //交叉矩形的面积
        
        return a + b - c;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值