题目:
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.思路:
类似于打气球,先按照头排序,然后一个一个的遍历,如果不想交就更新区间,如果相交,end取较小的一个就可以。
bool cmp(const Interval& a,const Interval& b){
return a.start<b.start?1:0;
}
class Solution {
public:
int eraseOverlapIntervals(vector<Interval>& intervals) {
int n = intervals.size();
if(n == 0) return 0;
sort(intervals.begin(),intervals.end(),cmp);
int re = 0;
int start = intervals[0].start, end = intervals[0].end, i = 1;
while(i<n){
if(intervals[i].start>=end){
end = intervals[i].end;
} else {
re++;
if(intervals[i].end<end) end = intervals[i].end;
}
i++;
}
return re;
}
};