 # 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.

O(n)

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)

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;
}

}
}``````

0 人关注
4 篇文章