原题
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if(intervals.empty())
return 0;
sort(intervals.begin(),intervals.end(),[](vector<int> a, vector<int> b){
return a[0] < b[0];
});
sort(intervals.begin(), intervals.end(), [](vector<int> a, vector<int> b){
return a[1] < b[1];
}); // 将区间按后一个排序
// for(int i = 0;i < intervals.size();i++)
// cout<<intervals[i][0]<<intervals[i][1]<<endl;
int total = 0, prev = intervals[0][1];
for(int i = 1;i < intervals.size(); i++){
if(prev > intervals[i][0])
total++;
else{
prev = intervals[i][1];
}
}
return total;
}
};
int main(){
Solution solution;
int result;
vector<vector<int> > intervals = {{1,2},{2,3},{3,4},{1,3}};
result = solution.eraseOverlapIntervals(intervals);
cout<<result<<endl;
return result;
}
思路
先把所有区间按头尾最小排序,再从前面向后找不重复的区间,
问题
为什么按后一个排序,看力扣里这个解答吧https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/solution/tu-jie-tan-tao-wei-shi-yao-yao-an-qu-jian-de-you-d/