无重叠区间
题目链接:https://leetcode-cn.com/problems/non-overlapping-intervals/submissions/
题目描述:
题解:
排序:
1.按左边界排序,从右往左遍历,左值越大越好。
2.按右边界排序,从左往右遍历,右值越小越好。
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;
}
};