Non-overlapping Intervals

来源:互联网 发布:java邮箱格式验证方法 编辑:程序博客网 时间:2024/06/05 08:40

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.

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.
解析:

首先按起点start进行排序,用一个变量记录最后结束的点的pos,如果新的区间起点小于pos,则更新pos到min(pos,end)的值,此时删除的次数ans++,典型的贪心解法。

代码:

/** * Definition for an interval. * struct Interval { *     int start; *     int end; *     Interval() : start(0), end(0) {} *     Interval(int s, int e) : start(s), end(e) {} * }; */class Solution {public:    static bool cmp(Interval a,Interval b)    {        if (a.start<b.start)        {            return true;        }        if (a.start==b.start)        {            return a.end<b.end;        }        return false;                            }    int eraseOverlapIntervals(vector<Interval>& intervals) {        if (intervals.empty())        return 0;        sort(intervals.begin(),intervals.end(),cmp);        int lastpoint=intervals[0].start;        int ans=0;        for (int i=0; i<intervals.size(); i++)        {            if (lastpoint<=intervals[i].start)            {                lastpoint=intervals[i].end;                continue;            }            ans++;            lastpoint=min(lastpoint,intervals[i].end);        }        return ans;    }};


0 0
原创粉丝点击