判断两个矩形相交的经典问题.
两种方法:
- 判断两个矩形不相交,然后取反.
- 两个矩形如果相交,必定长和宽两维都相交,那么就可以分别看每一维相交否.
# approach 1 class Solution(object): def isRectangleOverlap(self, rec1, rec2): """ :type rec1: List[int] :type rec2: List[int] :rtype: bool """ l1, r1, l2, r2 = rec1[0], rec1[2], rec2[0], rec2[2] b1, t1, b2, t2 = rec1[1], rec1[3], rec2[1], rec2[3] return not (r1 <= l2 or l1 >= r2 or b1 >= t2 or t1 <= b2)
# approach 2 class Solution(object): def isRectangleOverlap(self, rec1, rec2): """ :type rec1: List[int] :type rec2: List[int] :rtype: bool """ l1, r1, l2, r2 = rec1[0], rec1[2], rec2[0], rec2[2] b1, t1, b2, t2 = rec1[1], rec1[3], rec2[1], rec2[3] return (max(l1, l2) < min(r1, r2)) and (max(b1, b2) < min(t1, t2))