題目出處
難度
easy
題目分類
Math, Geometry
2026-09-27 一刷
個人範例程式碼 - 一刷 (2026/09/27)
class Solution:
def isRectangleOverlap(self, rec1: list[int], rec2: list[int]) -> bool:
# bottom-left, top-right
rec1_x1, rec1_y1, rec1_x2, rec1_y2 = rec1
rec2_x1, rec2_y1, rec2_x2, rec2_y2 = rec2
# use opposite method to check
# rec2 in the left of rec1: rec2_x2 <= rec1_x1
# rec2 in the right of rec1: rec1_x2 <= rec2_x1
# rec2 in the up of rec1: rec1_y2 <= rec2_y1
# rec2 in the down of rec1: rec2_y2 <= rec1_y1
non_overlap = (rec2_x2 <= rec1_x1) or \
(rec1_x2 <= rec2_x1) or \
(rec1_y2 <= rec2_y1) or \
(rec2_y2 <= rec1_y1)
return not non_overlap
算法說明
建議用反證法,當一個矩形只要在絕對上、下、左、右方,必不可能相交。
不建議直接解,因為有些 corner case 直接解會很麻煩,而且很有可能會漏考慮「兩矩形十字交叉」、或是「矩陣中矩陣」的重疊情況。
注意:這題我寫的過程中犯了一個額外的粗心
以為是 top-left, bottom-right (影像處理常見定位),但這題是一般的笛卡兒座標系統,往左往下才是越小
Time Complexity
O(1)
Space Complexity
O(1)
Boundary conditions
需留意「兩矩形十字交叉」、或是「矩陣中矩陣」的重疊情況。
因此推薦用反證法。
Reference
<待補>