-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0435-non-overlapping-intervals.cpp
48 lines (41 loc) · 1.53 KB
/
0435-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
40
41
42
43
44
45
46
47
48
// 54 / 58 test cases passed.
/*
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
unordered_map<string, int> dp;
auto gen_key = [](auto i, auto j) {
return to_string(i) + "-" + to_string(j);
};
function<int(int, int)> go = [&](auto i, auto to) {
if (i == intervals.size()) return 0;
auto key = gen_key(i, to);
if (dp.count(key)) return dp[key];
int calc = go(i + 1, to);
if (to <= intervals[i][0]) {
auto take = 1 + go(i + 1, intervals[i][1]);
calc = max(calc, take);
}
return dp[key] = calc;
};
return intervals.size() - go(0, -100000);
}
};
*/
// if two intervals are overlapping, we want to remove the interval that has the longer end point -- the longer interval will always overlap with more or the same number of future intervals compared to the shorter one
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [&](vector<int>& a, vector<int>& b) {
return a[1] < b[1];
});
int prevMax = INT_MIN, res = 0;
for (auto interval: intervals) {
auto left = interval[0], right = interval[1];
if (left < prevMax) res++;
else prevMax = max(prevMax, right);
}
return res;
}
};