LeetCode 题解工作台
检查是否区域内所有整数都被覆盖
给你一个二维整数数组 ranges 和两个整数 left 和 right 。每个 ranges[i] = [start i , end i ] 表示一个从 start i 到 end i 的 闭区间 。 如果闭区间 [left, right] 内每个整数都被 ranges 中 至少一个 区间覆盖,那…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以使用差分数组的思想,创建一个长度为 的差分数组 。 接下来,我们遍历数组 ,对于每个区间 $[l, r]$,我们令 自增 ,而 $\textit{diff}[r + 1]$ 自减 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个二维整数数组 ranges 和两个整数 left 和 right 。每个 ranges[i] = [starti, endi] 表示一个从 starti 到 endi 的 闭区间 。
如果闭区间 [left, right] 内每个整数都被 ranges 中 至少一个 区间覆盖,那么请你返回 true ,否则返回 false 。
已知区间 ranges[i] = [starti, endi] ,如果整数 x 满足 starti <= x <= endi ,那么我们称整数x 被覆盖了。
示例 1:
输入:ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5 输出:true 解释:2 到 5 的每个整数都被覆盖了: - 2 被第一个区间覆盖。 - 3 和 4 被第二个区间覆盖。 - 5 被第三个区间覆盖。
示例 2:
输入:ranges = [[1,10],[10,20]], left = 21, right = 21 输出:false 解释:21 没有被任何一个区间覆盖。
提示:
1 <= ranges.length <= 501 <= starti <= endi <= 501 <= left <= right <= 50
解题思路
方法一:差分数组
我们可以使用差分数组的思想,创建一个长度为 的差分数组 。
接下来,我们遍历数组 ,对于每个区间 ,我们令 自增 ,而 自减 。
接着,我们遍历差分数组 ,维护一个前缀和 ,对于每个位置 ,我们令 自增 ,如果 且 ,则说明区间 中有一个整数 没有被覆盖,返回 。
如果遍历完差分数组 后都没有返回 ,则说明区间 中的每个整数都被 中至少一个区间覆盖,返回 。
时间复杂度 ,空间复杂度 。其中 是数组 的长度,而 是区间的最大值,本题中 。
class Solution:
def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:
diff = [0] * 52
for l, r in ranges:
diff[l] += 1
diff[r + 1] -= 1
s = 0
for i, x in enumerate(diff):
s += x
if s <= 0 and left <= i <= right:
return False
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate shows understanding of array iteration techniques.
- question_mark
The candidate demonstrates awareness of optimizing brute-force solutions.
- question_mark
The candidate considers the use of advanced data structures for improving performance.
常见陷阱
外企场景- error
Overcomplicating the solution with unnecessary data structures for small inputs.
- error
Forgetting to check coverage for every integer between left and right.
- error
Confusing inclusive and exclusive range bounds when verifying coverage.
进阶变体
外企场景- arrow_right_alt
What if the intervals can overlap?
- arrow_right_alt
How would you approach the problem if the range size was very large?
- arrow_right_alt
Can the solution be optimized if ranges are sorted?