836. 矩形重叠
题目描述
矩形以列表 [x1, y1, x2, y2]
的形式表示,其中 (x1, y1)
为左下角的坐标,(x2, y2)
是右上角的坐标。矩形的上下边平行于 x 轴,左右边平行于 y 轴。
如果相交的面积为 正 ,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。
给出两个矩形 rec1
和 rec2
。如果它们重叠,返回 true
;否则,返回 false
。
示例 1:
- 输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3]
- 输出:true
示例 2:
- 输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1]
- 输出:false
示例 3:
- 输入:rec1 = [0,0,1,1], rec2 = [2,2,3,3]
- 输出:false
提示:
rect1.length == 4
rect2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1
和rec2
表示一个面积不为零的有效矩形
解法
方法一:判断不重叠的情况
我们记矩形
那么当满足以下任一条件时,矩形
- 满足
y 3 ≥ " role="presentation" style="position: relative;">,即y 2 r e c 2 " role="presentation" style="position: relative;"> 在r e c 1 " role="presentation" style="position: relative;"> 的上方; - 满足
y 4 ≤ " role="presentation" style="position: relative;">,即y 1 r e c 2 " role="presentation" style="position: relative;"> 在r e c 1 " role="presentation" style="position: relative;"> 的下方; - 满足
x 3 ≥ " role="presentation" style="position: relative;">,即x 2 r e c 2 " role="presentation" style="position: relative;"> 在r e c 1 " role="presentation" style="position: relative;"> 的右方; - 满足
x 4 ≤ " role="presentation" style="position: relative;">,即x 1 r e c 2 " role="presentation" style="position: relative;"> 在r e c 1 " role="presentation" style="position: relative;"> 的左方。
当以上条件都不满足时,矩形
时间复杂度
方法二:检查区域
如果两个矩形重叠,那么它们重叠的区域一定也是一个矩形,那么这代表了两个矩形与
矩形 rec1 和 rec2 的水平边投影到
时间复杂度:
Python3
方法一:
- class Solution:
- def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
- x1, y1, x2, y2 = rec1
- x3, y3, x4, y4 = rec2
- return not (y3 >= y2 or y4 <= y1 or x3 >= x2 or x4 <= x1)
方法二:
- class Solution:
- def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
- def intersect(p_left, p_right, q_left, q_right):
- return min(p_right, q_right) > max(p_left, q_left)
- return (intersect(rec1[0], rec1[2], rec2[0], rec2[2]) and
- intersect(rec1[1], rec1[3], rec2[1], rec2[3]))
C++
方法一:
- 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 !(y3 >= y2 || y4 <= y1 || x3 >= x2 || x4 <= x1);
- }
- };
方法二:
- class Solution {
- public:
- bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
- return (min(rec1[2], rec2[2]) > max(rec1[0], rec2[0]) &&
- min(rec1[3], rec2[3]) > max(rec1[1], rec2[1]));
- }
- };