无重叠区间

题目链接:https://leetcode-cn.com/problems/non-overlapping-intervals/submissions/
题目描述:
无重叠区间

题解:

class Solution {
public:

    static bool cmp(vector<int> &a, vector<int> &b)  //按右边界排序
    {
        return a[1] < b[1];
    }
    int eraseOverlapIntervals(vector<vector<int>>& intervals) {
        if(intervals.size() == 0)
            return 0;
        int uncross = 1;     //记录非重叠区间个数
        sort(intervals.begin(), intervals.end(), cmp);
        int position = intervals[0][1];      //记录当前节点的右边界
        for(int i = 1; i < intervals.size(); i++)
        {
            if(position <= intervals[i][0])    //如果当前节点左边界大于或等于上一个节点的右边界,则当前节点与上一个节点未重叠
            {
                uncross++;
                position = intervals[i][1];
            }
        }

        return intervals.size() - uncross;

    }
};
上一篇:合并区间


下一篇:Linux下alias命令