小拳头的博客

临渊羡鱼、不如退而结网

【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.


题目解读:求两个矩阵的总面积(即两个矩阵面积 - 覆盖的面积)


思路:分情况讨论即可


c++代码(32ms,56.67%)

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        if(C<E || G<A || H<B || D<F)
            return (C-A)*(D-B)+(G-E)*(H-F);
        else{
            //算出长和高 
            int length,height; //长,高
            if(A<=E && E<=C && C<=G)
                length=C-E;
            else if(A<=E && E<=G && G<=C)
                length=G-E;
            else if(E<=A && A<=G && G<=C)
                length=G-A;
            else 
                length=C-A;
            
            if(D>=H && H>=B && B>=F)
                height=H-B;
            else if(D>=H && H>=F && F>=B)
                height=H-F;
            else if(H>=D && D>=F && F>=B)
                height=D-F;
            else
                height=D-B;
                
            return (C-A)*(D-B)+(G-E)*(H-F)-length*height;
    
        }
            
    }
};


更简洁的代码

int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    int left = max(A,E), right = max(min(C,G), left);
    int bottom = max(B,F), top = max(min(D,H), bottom);
    return (C-A)*(D-B) - (right-left)*(top-bottom) + (G-E)*(H-F);
}



阅读更多
版权声明:本文为博主原创文章,转载请标明原文地址,谢谢 ^_^ https://blog.csdn.net/xiaoquantouer/article/details/51746835
文章标签: leetcode
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭