LeetCode 题解工作台
无重叠区间
给定一个区间的集合 intervals ,其中 intervals[i] = [start i , end i ] 。返回 需要移除区间的最小数量,使剩余区间互不重叠 。 注意 只在一点上接触的区间是 不重叠的 。例如 [1, 2] 和 [2, 3] 是不重叠的。 示例 1: 输入: interva…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们首先将区间按照右边界升序排序,用一个变量 记录上一个区间的右边界,用一个变量 记录需要移除的区间数量,初始时 $\textit{ans} = \textit{intervals.length}$。 然后遍历区间,对于每一个区间:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定一个区间的集合 intervals ,其中 intervals[i] = [starti, endi] 。返回 需要移除区间的最小数量,使剩余区间互不重叠 。
注意 只在一点上接触的区间是 不重叠的。例如 [1, 2] 和 [2, 3] 是不重叠的。
示例 1:
输入: intervals = [[1,2],[2,3],[3,4],[1,3]] 输出: 1 解释: 移除 [1,3] 后,剩下的区间没有重叠。
示例 2:
输入: intervals = [ [1,2], [1,2], [1,2] ] 输出: 2 解释: 你需要移除两个 [1,2] 来使剩下的区间没有重叠。
示例 3:
输入: intervals = [ [1,2], [2,3] ] 输出: 0 解释: 你不需要移除任何区间,因为它们已经是无重叠的了。
提示:
1 <= intervals.length <= 105intervals[i].length == 2-5 * 104 <= starti < endi <= 5 * 104
解题思路
方法一:排序 + 贪心
我们首先将区间按照右边界升序排序,用一个变量 记录上一个区间的右边界,用一个变量 记录需要移除的区间数量,初始时 。
然后遍历区间,对于每一个区间:
- 若当前区间的左边界大于等于 ,说明该区间无需移除,直接更新 为当前区间的右边界,然后将 减一;
- 否则,说明该区间需要移除,不需要更新 和 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为区间的数量。
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort(key=lambda x: x[1])
ans = len(intervals)
pre = -inf
for l, r in intervals:
if pre <= l:
ans -= 1
pre = r
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you consider intervals that only touch at endpoints as overlapping?
- question_mark
Can you optimize the DP solution using a greedy approach for larger inputs?
- question_mark
What is the trade-off between tracking maximum intervals kept vs. counting removals directly?
常见陷阱
外企场景- error
Assuming intervals touching at endpoints overlap, which leads to extra removals.
- error
Not sorting intervals properly before applying DP or greedy approach, causing incorrect state updates.
- error
Attempting a brute-force check of all subsets, which exceeds time limits for large inputs.
进阶变体
外企场景- arrow_right_alt
Find the maximum number of non-overlapping intervals instead of minimum removals.
- arrow_right_alt
Allow intervals with equal start and end times and count how many need removal.
- arrow_right_alt
Apply the same logic to weighted intervals where each interval has a value and the goal is maximum total value non-overlapping.