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
Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.
求两个矩形覆盖的面积。
假如没有重叠,直接算俩矩形面积。
假如有重叠,只要两个矩形面积扣除重合部分的面积就可以了。
难点在于如何判断有没有重叠。
重叠的情况实在有点多,我考虑了半天还是没考虑好各种情况。
然后看了下情况,有点巧妙…根本想不到…
说不太清楚,直接看代码吧。

class Solution {
public:
    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);
        int s1 = (C-A) * (D-B) + (G-E) * (H-F);
        int s2 = (right - left) * (top - bottom);
        return s1 - s2;
    }
};

你可能感兴趣的:(Rectangle Area)