LeetCode 题解工作台
完美矩形
给你一个数组 rectangles ,其中 rectangles[i] = [x i , y i , a i , b i ] 表示一个坐标轴平行的矩形。这个矩形的左下顶点是 (x i , y i ) ,右上顶点是 (a i , b i ) 。 如果所有矩形一起精确覆盖了某个矩形区域,则返回 true…
5
题型
4
代码语言
3
相关题
当前训练重点
困难 · 数组·哈希·扫描
答案摘要
class Solution: def isRectangleCover(self, rectangles: List[List[int]]) -> bool:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个数组 rectangles ,其中 rectangles[i] = [xi, yi, ai, bi] 表示一个坐标轴平行的矩形。这个矩形的左下顶点是 (xi, yi) ,右上顶点是 (ai, bi) 。
如果所有矩形一起精确覆盖了某个矩形区域,则返回 true ;否则,返回 false 。
示例 1:
输入:rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] 输出:true 解释:5 个矩形一起可以精确地覆盖一个矩形区域。
示例 2:
输入:rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] 输出:false 解释:两个矩形之间有间隔,无法覆盖成一个矩形。
示例 3:
输入:rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] 输出:false 解释:因为中间有相交区域,虽然形成了矩形,但不是精确覆盖。
提示:
1 <= rectangles.length <= 2 * 104rectangles[i].length == 4-105 <= xi < ai <= 105-105 <= yi < bi <= 105
解题思路
方法一
class Solution:
def isRectangleCover(self, rectangles: List[List[int]]) -> bool:
area = 0
minX, minY = rectangles[0][0], rectangles[0][1]
maxX, maxY = rectangles[0][2], rectangles[0][3]
cnt = defaultdict(int)
for r in rectangles:
area += (r[2] - r[0]) * (r[3] - r[1])
minX = min(minX, r[0])
minY = min(minY, r[1])
maxX = max(maxX, r[2])
maxY = max(maxY, r[3])
cnt[(r[0], r[1])] += 1
cnt[(r[0], r[3])] += 1
cnt[(r[2], r[3])] += 1
cnt[(r[2], r[1])] += 1
if (
area != (maxX - minX) * (maxY - minY)
or cnt[(minX, minY)] != 1
or cnt[(minX, maxY)] != 1
or cnt[(maxX, maxY)] != 1
or cnt[(maxX, minY)] != 1
):
return False
del cnt[(minX, minY)], cnt[(minX, maxY)], cnt[(maxX, maxY)], cnt[(maxX, minY)]
return all(c == 2 or c == 4 for c in cnt.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for scanning all rectangles and managing corners in a hash set, and space complexity is O(n) for storing unique corners in the hash set. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate correctly identifies using corner counting to detect overlaps and gaps.
- question_mark
Candidate computes bounding box and total area to validate perfect rectangle efficiently.
- question_mark
Candidate leverages hash set operations for quick corner addition/removal to simplify checks.
常见陷阱
外企场景- error
Failing to handle duplicate corners leads to false positives for overlaps.
- error
Neglecting to check area consistency can miss gaps even when corners match.
- error
Assuming rectangles are sorted; unordered rectangles require proper hash-based corner tracking.
进阶变体
外企场景- arrow_right_alt
Check for perfect square cover instead of general rectangle.
- arrow_right_alt
Allow rectangles with floating point coordinates and detect exact cover.
- arrow_right_alt
Return coordinates of missing or overlapping areas instead of boolean.