class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
}
};
435. 无重叠区间
给定一个区间的集合 intervals
,其中 intervals[i] = [starti, endi]
。返回 需要移除区间的最小数量,使剩余区间互不重叠 。
示例 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 <= 105
intervals[i].length == 2
-5 * 104 <= starti < endi <= 5 * 104
相似题目
原站题解
java 解法, 执行用时: 54 ms, 内存消耗: 94.2 MB, 提交时间: 2023-05-31 15:30:36
class Solution { public int eraseOverlapIntervals(int[][] intervals) { if (intervals.length == 0) { return 0; } Arrays.sort(intervals, new Comparator<int[]>() { public int compare(int[] interval1, int[] interval2) { return interval1[1] - interval2[1]; } }); int n = intervals.length; int right = intervals[0][1]; int ans = 1; for (int i = 1; i < n; ++i) { if (intervals[i][0] >= right) { ++ans; right = intervals[i][1]; } } return n - ans; } }
javascript 解法, 执行用时: 212 ms, 内存消耗: 72.7 MB, 提交时间: 2023-05-31 15:30:24
/** * @param {number[][]} intervals * @return {number} */ var eraseOverlapIntervals = function(intervals) { if (!intervals.length) { return 0; } intervals.sort((a, b) => a[1] - b[1]); const n = intervals.length; let right = intervals[0][1]; let ans = 1; for (let i = 1; i < n; ++i) { if (intervals[i][0] >= right) { ++ans; right = intervals[i][1]; } } return n - ans; };
golang 解法, 执行用时: 200 ms, 内存消耗: 14.9 MB, 提交时间: 2023-05-31 15:30:11
func eraseOverlapIntervals(intervals [][]int) int { n := len(intervals) if n == 0 { return 0 } sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] }) ans, right := 1, intervals[0][1] for _, p := range intervals[1:] { if p[0] >= right { ans++ right = p[1] } } return n - ans }
python3 解法, 执行用时: 260 ms, 内存消耗: 49.3 MB, 提交时间: 2023-05-31 15:29:58
# 贪心 class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: if not intervals: return 0 intervals.sort(key=lambda x: x[1]) n = len(intervals) right = intervals[0][1] ans = 1 for i in range(1, n): if intervals[i][0] >= right: ans += 1 right = intervals[i][1] return n - ans