玩命加载中 . . .

223-矩形面积


LeetCode 223. Rectangle Area

LeetCode-223

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).

The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).

Example 1:

Rectangle Area
Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output: 45

method

要计算覆盖的总面积,需要先计算出重叠部分的面积,再用总面积减去重叠面积

dx<0的话,一定没有重叠,所以直接返回面积,但是dx>0也不一定有重叠,还得判断y方向有没有重叠,如果dy>0,那就一定有重叠了

int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
    int area = (ax2-ax1) * (ay2-ay1) + (bx2-bx1) * (by2-by1);
    int dx = min(ax2, bx2) - max(ax1, bx1);
    if (dx < 0) return area;    // x方向没有重叠
    int dy = min(ay2, by2) - max(ay1, by1);
    if (dy < 0) return area;    // y方向没有重叠
    return area - dx * dy;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录