加载中...
836-矩形重叠(Rectangle Overlap)
发表于:2021-12-03 | 分类: 简单
字数统计: 1k | 阅读时长: 4分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/rectangle-overlap

英文原文

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 return false.

 

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:

  • rect1.length == 4
  • rect2.length == 4
  • -109 <= rec1[i], rec2[i] <= 109
  • rec1 and rec2 represent a valid rectangle with a non-zero area.

中文题目

矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。矩形的上下边平行于 x 轴,左右边平行于 y 轴。

如果相交的面积为 ,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。

给出两个矩形 rec1rec2 。如果它们重叠,返回 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
  • rec1rec2 表示一个面积不为零的有效矩形

通过代码

高赞题解

矩形重叠要考虑的情况很多,两个矩形的重叠可能有好多种不同的形态。这道题如果用蛮力做的话,很容易遗漏掉某些情况,导致出错。

矩形重叠是二维的问题,所以情况很多,比较复杂。为了简化问题,我们可以考虑将二维问题转化为一维问题。既然题目中的矩形都是平行于坐标轴的,我们将矩形投影到坐标轴上:

project-overlap

矩形投影到坐标轴上,就变成了区间。稍加思考,我们发现:两个互相重叠的矩形,它们在 $x$ 轴和 $y$ 轴上投影出的区间也是互相重叠的。这样,我们就将矩形重叠问题转化成了区间重叠问题。

区间重叠是一维的问题,比二维问题简单很多。我们可以穷举出两个区间所有可能的 6 种关系:

interval-relation

可以看到,区间的 6 种关系中,不重叠只有两种情况,判断不重叠更简单。假设两个区间分别是 [s1, e1][s2, e2] 的话,区间不重叠的两种情况就是 e1 <= s2e2 <= s1

interval-overlap

我们就得到区间不重叠的条件:e1 <= s2 || e2 <= s1。将条件取反即为区间重叠的条件。

这样,我们就可以写出判断矩形重叠的代码了:

[]
bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) { bool x_overlap = !(rec1[2] <= rec2[0] || rec2[2] <= rec1[0]); bool y_overlap = !(rec1[3] <= rec2[1] || rec2[3] <= rec1[1]); return x_overlap && y_overlap; }
[]
public boolean isRectangleOverlap(int[] rec1, int[] rec2) { boolean x_overlap = !(rec1[2] <= rec2[0] || rec2[2] <= rec1[0]); boolean y_overlap = !(rec1[3] <= rec2[1] || rec2[3] <= rec1[1]); return x_overlap && y_overlap; }
[]
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: x_overlap = not(rec1[2] <= rec2[0] or rec2[2] <= rec1[0]) y_overlap = not(rec1[3] <= rec2[1] or rec2[3] <= rec1[1]) return x_overlap and y_overlap

如果你觉得本文对你有帮助,欢迎关注我的公众号《面向大象编程》,其中的《LeetCode 例题精讲》系列文章正在写作,不仅有题解,更能让你学会解题的通用思路,举一反三!

wechat

统计信息

通过次数 提交次数 AC比率
38546 80211 48.1%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言

相似题目

题目 难度
矩形面积 中等
上一篇:
835-图像重叠(Image Overlap)
下一篇:
837-新 21 点(New 21 Game)
本文目录
本文目录