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.

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

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);
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/0f14e1d633f1
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞