日期:2026年9月14日
LeetCode 題目連結:836. Rectangle Overlap
解題想法
簡單題,題目給兩個長度為 $4$ 的陣列,代表長方形的頂點坐標,其中 $(x1, y1)$ 為左下方頂點坐標,$(x2, y2)$ 為右上方頂點坐標,回傳這兩個長方形是否重疊,如果只是頂點或邊互相接觸不算重疊。這題反過來寫比較簡單,列出 $4$ 種不重疊的狀況,只要 $4$ 種狀況其中一種成立就不會重疊,外面再加上 not,回傳反過來的狀態。假設兩個長方形的頂點分別為 $(x1, y1, x2, y2), (x3, y3, x4, y4)$,不重疊的狀況為:
- $x1 \geq x4$,長方形 1 在長方形 2 的右側。
- $y1 \geq y4$,長方形 1 在長方形 2 的上方。
- $x2 \leq x3$,長方形 1 在長方形 2 的左側。
- $y2 \leq y3$,長方形 1 在長方形 2 的下方。
Python 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 19.36 MB, beats 19.53%.
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
x1, y1, x2, y2 = rec1
x3, y3, x4, y4 = rec2
return not (x2 <= x3 or x1 >= x4 or y1 >= y4 or y2 <= y3)
C++ 程式碼
Runtime: 0 ms, beats 100.00%. Memory: 9.04 MB, beats 100.00%.
class Solution {
public:
bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
int x1 = rec1[0], y1 = rec1[1], x2 = rec1[2], y2 = rec1[3];
int x3 = rec2[0], y3 = rec2[1], x4 = rec2[2], y4 = rec2[3];
return !(x2 <= x3 || x1 >= x4 || y1 >= y4 || y2 <= y3);
}
};
C 語言程式碼
Runtime: 0 ms, beats 100.00%. Memory: 8.60 MB, beats 54.43%.
bool isRectangleOverlap(int* rec1, int rec1Size, int* rec2, int rec2Size) {
int x1 = rec1[0], y1 = rec1[1], x2 = rec1[2], y2 = rec1[3];
int x3 = rec2[0], y3 = rec2[1], x4 = rec2[2], y4 = rec2[3];
return !(x1 >= x4 || x2 <= x3 || y1 >= y4 || y2 <= y3);
}
沒有留言:
張貼留言