forked from shijbian/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrussian-doll-envelopes.cpp
More file actions
28 lines (25 loc) · 874 Bytes
/
russian-doll-envelopes.cpp
File metadata and controls
28 lines (25 loc) · 874 Bytes
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
// Time: O(nlogn + nlogk) = O(nlogn), k is the length of the result.
// Space: O(1)
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
vector<int> result;
sort(envelopes.begin(), envelopes.end(), // O(nlogn)
[](const pair<int, int>& a, const pair<int, int>& b) {
if (a.first == b.first) {
return a.second > b.second;
}
return a.first < b.first;
});
for (const auto& envelope : envelopes) {
const auto target = envelope.second;
auto it = lower_bound(result.begin(), result.end(), target); // O(logk)
if (it == result.end()) {
result.emplace_back(target);
} else {
*it = target;
}
}
return result.size();
}
};