836. 矩形重叠
836. 矩形重叠
题目
An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise returnfalse.
Example 1:
Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true
Example 2:
Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false
Example 3:
Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]
Output: false
Constraints:
rec1.length == 4rec2.length == 4-10^9 <= rec1[i], rec2[i] <= 10^9rec1andrec2represent a valid rectangle with a non-zero area.
题目大意
矩形以列表 [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 == 4rect2.length == 4-10^9 <= rec1[i], rec2[i] <= 10^9rec1和rec2表示一个面积不为零的有效矩形
解题思路
边界条件:矩形退化成线或点
- 如果矩形的宽或高为 0,则矩形退化成一条线或一个点,此时矩形不可能重叠,可以提前排除这种情况。
矩形不重叠的条件
- 两个矩形在以下情况下不会重叠:
rec1在rec2的左边:rec1[2] <= rec2[0](即rec1的右边界小于等于rec2的左边界)。rec1在rec2的右边:rec2[2] <= rec1[0](即rec2的右边界小于等于rec1的左边界)。rec1在rec2的上方:rec1[1] >= rec2[3](即rec1的下边界大于等于rec2的上边界)。rec1在rec2的下方:rec2[1] >= rec1[3](即rec2的下边界大于等于rec1的上边界)。
- 两个矩形在以下情况下不会重叠:
矩形重叠的条件
- 矩形重叠的条件就是它们上述所有不重叠条件的“取反”。
复杂度分析
- 时间复杂度:
O(1),代码中只进行了常数级别的比较操作。 - 空间复杂度:
O(1),没有使用额外空间。
代码
/**
* @param {number[]} rec1
* @param {number[]} rec2
* @return {boolean}
*/
var isRectangleOverlap = function (rec1, rec2) {
// 边界情况:矩形退化成线或点,无法重叠
if (
rec1[0] == rec1[2] ||
rec1[1] == rec1[3] ||
rec2[0] == rec2[2] ||
rec2[1] == rec2[3]
) {
return false;
}
// 判断矩形是否重叠
return !(
rec1[2] <= rec2[0] || // rec1 在 rec2 左侧
rec2[2] <= rec1[0] || // rec1 在 rec2 右侧
rec1[3] <= rec2[1] || // rec1 在 rec2 下方
// rec1 在 rec2 上方
rec2[3] <= rec1[1]
);
};
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 223 | 矩形面积 | [✓] | 几何 数学 | 🟠 | 🀄️ 🔗 |
