-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathnon-overlapping-intervals.cpp
39 lines (37 loc) · 1.09 KB
/
non-overlapping-intervals.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
// Time: O(nlogn)
// Space: O(1)
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { return a[1] < b[1]; });
int result = 0, right = numeric_limits<int>::min();
for (const auto& x : intervals) {
if (x[0] < right) {
++result;
} else {
right = x[1];
}
}
return result;
}
};
// Time: O(nlogn)
// Space: O(1)
class Solution2 {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) { return a[0] < b[0]; });
int result = 0, prev = 0;
for (int i = 1; i < intervals.size(); ++i) {
if (intervals[i][0] < intervals[prev][1]) {
if (intervals[i][1] < intervals[prev][1]) {
prev = i;
}
++result;
} else {
prev = i;
}
}
return result;
}
};