LeetCode 223. Rectangle Area

Description

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.


img

Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.

Analysis

Firstly calculate the area of two rectangle and then remove the overlapping area. When thinking, figuring out all situations by drawing some is of help. And the two dimensions should be considered respectively.

Code

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int com_x = 0, com_y = 0;
        if (A < G && C > E)
            com_x = min(C, G) - max(A, E);
        if (B < H && D > F)
            com_y = min(D, H) - max(B, F);
        return (C - A) * (D - B) + (G - E) * (H - F) - com_x * com_y;
    }
};

Appendix

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章