forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-increasing-subsequence.cpp
44 lines (37 loc) · 1.02 KB
/
longest-increasing-subsequence.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
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
/**
* @param nums: The integer array
* @return: The length of LIS (longest increasing subsequence)
*/
void insert(vector<int>& LIS, int target) {
int left = 0, right = LIS.size() - 1;
auto comp = [](int x, int target) { return x <= target; };
// Find the largest index "left" which satisfies LIS[left] <= target
while (left <= right) {
int mid = left + (right - left) / 2;
if (!comp(LIS[mid], target)) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
// If not found, append the target.
if (left == LIS.size()) {
LIS.emplace_back(target);
}
else {
LIS[left] = target;
}
}
int longestIncreasingSubsequence(vector<int> nums) {
vector<int> LIS;
for (auto& i : nums) {
insert(LIS, i);
}
return LIS.size();
}
};