leetcode——Non-overlapping Intervals

来源:互联网 发布:ubuntu翻译软件 编辑:程序博客网 时间:2024/06/05 22:34

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: 1Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.

Example 2:

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

Example 3:

Input: [ [1,2], [2,3] ]Output: 0Explanation: 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;}};
不懂为嘛,用迭代器写的反而耗时更长。。

0 0
原创粉丝点击