LeetCode 435. Non-overlapping Intervals
作者:互联网
LeetCode 435. Non-overlapping Intervals (无重叠区间)
题目
链接
https://leetcode.cn/problems/non-overlapping-intervals/
问题描述
给定一个区间的集合 intervals ,其中 intervals[i] = [starti, endi] 。返回 需要移除区间的最小数量,使剩余区间互不重叠 。
示例
输入: intervals = [[1,2],[2,3],[3,4],[1,3]]
输出: 1
解释: 移除 [1,3] 后,剩下的区间没有重叠。
提示
1 <= intervals.length <= 105
intervals[i].length == 2
-5 * 104 <= starti < endi <= 5 * 104
思路
同样贪心思想,找到右边界最小的,然后找下一个。
复杂度分析
时间复杂度 O(n)
空间复杂度 O(1)
代码
Java
public int eraseOverlapIntervals(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> {
return a[1] - b[1];
});
int count = 0;
int edge = Integer.MIN_VALUE;
for (int i = 0; i < intervals.length; i++) {
if (edge <= intervals[i][0]) {
edge = intervals[i][1];
} else {
count++;
}
}
return count;
}
标签:Non,int,复杂度,overlapping,intervals,移除,区间,435,LeetCode 来源: https://www.cnblogs.com/blogxjc/p/16417758.html