-
Notifications
You must be signed in to change notification settings - Fork 259
/
Copy pathlongest-increasing-subsequence.cpp
75 lines (63 loc) · 1.79 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Time: O(nlogn)
// Space: O(n)
// Binary search solution with STL.
class Solution {
public:
/**
* @param nums: The integer array
* @return: The length of LIS (longest increasing subsequence)
*/
int longestIncreasingSubsequence(vector<int> nums) {
vector<int> LIS;
for (const auto& i : nums) {
insert(&LIS, i);
}
return LIS.size();
}
private:
void insert(vector<int> *LIS, const int target) {
// Find the first index "left" which satisfies LIS[left] > target
auto it = upper_bound(LIS->begin(), LIS->end(), target);
// If not found, append the target.
if (it == LIS->end()) {
LIS->emplace_back(target);
} else {
*it = target;
}
}
};
// Binary search solution.
class Solution2 {
public:
/**
* @param nums: The integer array
* @return: The length of LIS (longest increasing subsequence)
*/
int longestIncreasingSubsequence(vector<int> nums) {
vector<int> LIS;
for (const auto& i : nums) {
insert(&LIS, i);
}
return LIS.size();
}
private:
void insert(vector<int> *LIS, const int target) {
int left = 0, right = LIS->size() - 1;
auto comp = [](int x, int target) { return x > target; };
// Find the first 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;
}
}
};