Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 223. Rectangle Area

Rain Hu

223. Rectangle Area


一、題目

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 tis top-right corner (bx2, by2).

Example 1:
rectangle-plane

Example 2:

Constraints:


二、分析

struct Rect {
    int x1,x2,y1,y2;
};

三、解題

1. Math

struct Rect {
    int x1,y1,x2,y2;
    Rect(int x1_, int y1_, int x2_, int y2_):x1(x1_),y1(y1_),x2(x2_),y2(y2_) {}
    int area() {
        return (x1 >= x2 || y1 >= y2) ? 0 : (x2 - x1) * (y2 - y1);      // 不重疊則回傳面積 0
    }
};
class Solution {
public:
    int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
        Rect a(ax1,ay1,ax2,ay2);
        Rect b(bx1,by1,bx2,by2);
        Rect c(max(ax1,bx1),
                max(ay1,by1),
                min(ax2,bx2),
                min(ay2,by2));
        return a.area() + b.area() - c.area();
    }
};

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2465. Number of Distinct Averages
Next
[LeetCode] 374. Guess Number Higher or Lower