您的位置:首页 > 移动开发

leetcode——Non-overlapping Intervals

2016-11-03 23:55 330 查看
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.


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.


解析:利用贪心算法求解,假设在某个区域,有n个区间重叠,则显然n个区间最后只能留下一个,而根据局部最优,势必留下end最小的最有利。根据这个思路,事先将数组排序,然后不断删去区间即可,时间复杂度为O(n).

class Solution {
public:
static bool cmp(Interval& a, Interval& b)
{
return a.end < b.end;
}
int eraseOverlapIntervals(vector<Interval>& intervals) {
if(!intervals.size())	return 0;
int num = 0;
sort(intervals.begin(), intervals.end(), cmp);
for(vector<Interval>::iterator i = intervals.begin(); i!=intervals.end(); i++)
while(i != intervals.end()-1 && i->end > (i+1)->start)
{
intervals.erase(i+1);
num ++;
}
return num;
}
};
不懂为嘛,用迭代器写的反而耗时更长。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息