Leetcode 223. Rectangle Area

作者: ShutLove | 来源:发表于2017-12-05 18:31 被阅读24次

    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.

    思路:
    求两个矩形的覆盖面积。如果两个矩形没有交叉,那么覆盖面积就是两个矩形的面积之和;如果有交叉,那么结果等于两个矩形的面积和剪去交叉的面积。
    交叉面积实质是求交叉面积的长和宽,长和宽其实是要求交叉面积的左右上下坐标。

    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        //相交
        int left = 0, right = 0, top = 0, bottom = 0;
        left = Math.max(A, E);
        right = Math.min(C, G);
        top = Math.min(D, H);
        bottom = Math.max(B, F);
    
        return (C - A) * (D - B) - (right - left) * (top - bottom) + (G - E) * (H - F);
    }

    相关文章

      网友评论

        本文标题:Leetcode 223. Rectangle Area

        本文链接:https://www.haomeiwen.com/subject/xuncixtx.html