Description:
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Solution:
先按照尾巴大小排个序
从尾巴开始考虑,贪心算法
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
int size = intervals.size(), amountRemoved = 0;
if (size <= 1) return 0;
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int> &b) {
return a[1] < b[1];
});
int previousEnd = intervals[0][1];
for (int i = 1; i < size; i++) {
if (intervals[i][0] < previousEnd) {
amountRemoved++;
} else {
previousEnd = intervals[i][1];
}
}
return amountRemoved;
}