[LeetCode] 435 Non-overlapping Intervals

时间:2023-01-19 14:46:18

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:

  1. You may assume the interval's end point is always bigger than its start point.
  2. 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.

Example 2:

Input: [ [1,2], [1,2], [1,2] ]

Output: 2

Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.

Example 3:

Input: [ [1,2], [2,3] ]

Output: 0

Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

这个题目和 http://www.cnblogs.com/javanerd/p/6068552.html 这道题目差不多,都可以对一个interval线段数组进行排序,然后用滑动窗口来解。

但是,因为涉及到一些比较复杂的条件判断,所以排序以后,直接用了双层循环去两两比较,同时用一个boolean数组记录出已经被踢出去的线段,用来提高效率。

代码如下:

public int eraseOverlapIntervals(Interval[] intervals) {
if (intervals.length == 0 || intervals.length == 1) {
return 0;
} else {
int result = 0;
int[] mark = new int[intervals.length];
Arrays.fill(mark, 0);
Arrays.sort(intervals, (o1, o2) -> {
if (o1.start == o2.start) {
return o2.end - o1.end;
} else {
return o1.start - o2.start;
}
}); //按照start从小到大,然后end从大到小排序.
for (int i = 0; i < intervals.length - 1; i++) {
if (mark[i] != 1) {
for (int j = i + 1; j < intervals.length; j++) {
if (mark[j] == 1) {
continue;
} else {
Interval left = intervals[i];
Interval right = intervals[j];
if (left.start == right.start) { //如果两个线段start一样,那么删掉end比较大的那个.
mark[i] = 1;
result++;
break;
} else if (left.end > right.start) { //如果两个线段有折叠
result++;
if (left.end <= right.end) { //如果右边的线段的end比较大,那么删掉右边线段,同时往后移动一位,继续比较下一个.
mark[j] = 1;
} else {
mark[i] = 1; //如果左边的线段的end比较大,那么删掉左边的.同时结束内存循环.
break;
}
} else { // left.end <= right.start,因为已经排序了,那么后面的start必然都比left.end大,提前终止循环
break;
}
}
}
}
}
return result;
}
}