forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main4.cpp
52 lines (38 loc) · 1.28 KB
/
main4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/// https://leetcode.com/problems/non-overlapping-intervals/description/
/// Author : liuyubobobo
/// Time : 2017-11-19
/// Updated: 2019-09-22
#include <iostream>
#include <vector>
using namespace std;
/// Greedy Algorithm based on ending point
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
if(intervals.size() == 0)
return 0;
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b){
if(a[1] != b[1]) return a[1] < b[1];
return a[0] < b[0];
});
int res = 1;
int pre = 0;
for(int i = 1 ; i < intervals.size() ; i ++)
if(intervals[i][0] >= intervals[pre][1]){
res ++;
pre = i;
}
return intervals.size() - res;
}
};
int main() {
vector<vector<int>> interval1 = {{1,2}, {2,3}, {3,4}, {1,3}};
cout << Solution().eraseOverlapIntervals(interval1) << endl;
vector<vector<int>> interval2 = {{1,2}, {1,2}, {1,2}};
cout << Solution().eraseOverlapIntervals(interval2) << endl;
vector<vector<int>> interval3 = {{1,2}, {2,3}};
cout << Solution().eraseOverlapIntervals(interval3) << endl;
return 0;
}