LeetCode 223: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.

找出2D平面上的两个矩形所覆盖的总面积。

如图所示,每个矩形都用左下角和右上角的点来定义。

假定所有点的定义都不超过int型变量的范围。


这道题我自己的想法是把所有情况都写出来,然而写了之后才发现太复杂,不可能是这种解法,于是去百度了一下矩形重叠的条件,这里总结了一下重叠的各种情况

这里只给出了重叠部分的坐标情况


左下角点坐标:(E,F)   横坐标为max(A,E) 纵坐标为max(B,F)

右上角点坐标:(C,D) 横坐标为min(C,G) 纵坐标为min(D,H)



左下角点坐标:(E,B)   横坐标为max(A,E) 纵坐标为max(B,F)

右上角点坐标:(C,H) 横坐标为min(C,G) 纵坐标为min(D,H)



左下角点坐标:(A,B)   横坐标为max(A,E) 纵坐标为max(B,F)

右上角点坐标:(G,H) 横坐标为min(C,G) 纵坐标为min(D,H)



左下角点坐标:(A,F)   横坐标为max(A,E) 纵坐标为max(B,F)

右上角点坐标:(G,D) 横坐标为min(C,G) 纵坐标为min(D,H)



左下角点坐标:(A,F)   横坐标为max(A,E) 纵坐标为max(B,F)

右上角点坐标:(G,D) 横坐标为min(C,G) 纵坐标为min(D,H)


由此可以总结出重叠部分的横坐标为max(A,E) 纵坐标为max(B,F),而要判断是否重叠,只需在计算面积的时候判断长或宽是否小于0即可。

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int temp=(min(C,G)-max(A,E))*(min(D,H)-max(B,F));
        if(min(C,G)<=max(A,E)||min(D,H)<=max(B,F))
            temp=0;
        return (C-A)*(D-B)+(G-E)*(H-F)-temp;
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值