[leetcode 223] Rectangle Area

Question:
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
Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.

分析:
暴力法:
最简单的情况就是排除几个特例情况,然后分析有重叠的情况。两种情况,有重叠,无重叠。
无重叠:横坐或是纵坐标没有交集。直接返回两个矩形的面积。
有重叠:对四个横坐标和四个纵坐标排序,横坐标中间的两个数的差值就是重叠部分的宽,纵坐标中间的两个数的差值就是重叠部分的高。
结果即为两个矩形面积和再减去重叠部分的面积。

不用排序的方法:
暴力法也可以解决问题,可以通过leetcode的测试,但是运行时间过长,如果不采用排序的方法:
第一步也是先把无重叠的部分优先判断;
第二步有重叠包含两种情况:
部分重叠;
其中一个矩阵完全重叠在另一个矩阵中。
重叠部分的宽 则 取自身宽度差 和 与另一个矩阵宽度差 的最小值,这样就包含了完全重叠的情况。

<span style="font-size:14px;">class Solution {
private:
    int area(int height, int width){
        return height*width;
    }
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        /*int result;
        int area1,area2,area3;
        area1 = area(D-B,C-A);
        area2 = area(H-F,G-E);
        
        if(E < A && F < B && G > C && H > D)
            return area2;
        if(A < E && B < F && C > G && D > H)
            return area1;
        if(A == E && B == F && C == G && D == H)
            return area1;
        if(C < E || G < A || F > D || H < B)
            return area1+area2;
        vector<int> Xsort{A,C,E,G};
        vector<int> Ysort{B,D,F,H};
        sort(Xsort.begin(),Xsort.end());
        sort(Ysort.begin(),Ysort.end());
        area3 = area(Ysort[2]-Ysort[1], Xsort[2]-Xsort[1]);
        return area1 + area2 - area3;*/
        int area1 = (C-A)*(D-B);
        int area2 = (G-E)*(H-F);
        if(C<=E || G<=A || D<=F ||B>=H){
        return area1+area2;
        }
        int width =  (A<=E)?min(C-E,G-E):min(C-A,G-A);
        int height = (B>=F)?min(D-B,H-B):min(D-F,H-F);
        return area1+area2-width*height;
        
    }
};</span>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值