天天看點

LeetCode 223. Rectangle AreaDescriptionAnalysisCodeAppendix

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.

LeetCode 223. Rectangle AreaDescriptionAnalysisCodeAppendix

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

  • Link: https://leetcode.com/problems/rectangle-area/
  • Run Time: 12ms
  • beats 99.47% submissions. Only simple problems like this may match my coding…