Non-overlapping Intervals
Given a collection of intervals, find the minimum number of intervals
you need to remove to make the rest of the intervals non-overlapping.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.
Logic
Sort array's elements by their end and delete sorted elements whose start are less than previous one's end.
Time Complexity
O(n)
Space Complexity
O(n)
Code
public class Solution {
public int eraseOverlapIntervals(Interval[] intervals) {
if (intervals.length == 0)
return 0;
PriorityQueue<Interval> pq = new PriorityQueue<Interval>(10, new MyComparator());
for(Interval it: intervals)
pq.add(it);
int endpoint = 0;
int count = 0;
while(pq.size()>1){
endpoint = pq.poll().end;
while(pq.size()>0&&pq.peek().start<endpoint){
pq.poll();
count++;
}
}
return count;
}
public class MyComparator implements Comparator<Interval>{
public int compare(Interval a, Interval b){
return a.end - b.end;
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。