LeetCode Exercise

Logo

This is my LeetCode exercise.
You can see all question I did here.

View the Project on GitHub YaoyuanHsu/LeetCode_Exercise

tags: leetcode Medium Math Geometry

223. Rectangle Area

Description

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).

Examples

Example 1:

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

Example 2:

Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 Output: 16

Constraints:

Code

#define Square(x1, x2, y1, y2) ((x2 - x1) * (y2 - y1))
#define Large1(a1, b1) (a1 < b1 ? b1 : a1)
#define Min2(a2, b2) (a2 < b2 ? a2 : b2)

int CrossDistance(int a1, int a2, int b1, int b2) {
    if ((b1 > a2) || (a1 > b2))
        return 0;
    return Min2(a2, b2) - Large1(a1, b1);
}

int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
    return Square(ax1, ax2, ay1, ay2) + Square(bx1, bx2, by1, by2) -
           CrossDistance(ax1, ax2, bx1, bx2) * CrossDistance(ay1, ay2, by1, by2);
}

Complexity

Space Time
$O(1)$ $O(1)$

Result