Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
You may assume the interval’s end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders “touching” but they don’t overlap each other.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
题目中给出了几个小区间,让去除最少数量的区间,使得剩下的区间没有overlap
overlap: 区间有重叠,哪怕是半个重叠也算 ex:[1,5], [4,7]
思路:
因为区间有左端点,右端点,判断的时候两者兼顾显然比较费时间,比如遇到如下情景
[1,3], [5, 7], [8,9], [2,5],遇到[2,5]的时候又要从前到后逐个查有没有overlap
可以看到之所以又要从头开始逐个 查是因为它的左端点在[5,7], [8,9]的前面,所以只需要让左端点按顺序出现就不需要逐个判断了
然后是右端点
比如刚开始出现了[1, 100], 后面依次是[1,2], [2, 3], [3, 4]
可以看到如果刚开始的区间定义在1~100的范围,那后面所有的小区间都要删除,就不满足题目中的删除最小数量的要求
所以每次都取较小的右端点,才能保证删除数量最小
而左端点因为是按升序排列的,小的左端点会在开始出现,后面不需要再更新左端点
如何判断overlap,只需要右端点 < 下一区间的左端点
题目中说Intervals like [1,2] and [2,3] have borders “touching” but they don’t overlap each other.,所以不需要用<=
public int eraseOverlapIntervals(int[][] intervals) {
if (intervals == null || intervals.length <= 1) {
return 0;
}
Arrays.sort(intervals, new Comparator() {
public int compare(Object o1, Object o2) {
return ((int[])o1)[0] - ((int[])o2)[0];
}
});
int right = intervals[0][1];
int res = 0;
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < right) {
res ++;
right = Math.min(right, intervals[i][1]);
continue;
}
if (intervals[i][1] > right) {
right = intervals[i][1];
}
}
return res;
}