Longest Increasing Subsequence[medium]
Description
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
Solution
具体分析见上一篇博客关于LIS问题的分析;
O(n*n)
int lengthOfLIS(vector<int>& nums) {
int l = nums.size();
if (l == 0) return l;
int f[l];
f[0] = 1;
for (int i = 1; i < l; i++) {
f[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]&&f[i] < f[j]+1) {
f[i] = f[j] + 1;
}
}
}
int max = f[0];
for (int i = 1; i < l; i++) {
if (f[i] > max) {
max = f[i];
}
}
return max;
}
O(n*logn)
int lengthOfLIS(vector<int>& nums) {
int l = nums.size();
if (l == 0) return l;
int B[l];
B[0] = nums[0];
int len = 1;
int pos = 0;
for (int i = 1; i < l; i++) {
if (nums[i] > B[len-1]) {
B[len] = nums[i];
len++;
} else {
pos = biSearch(B, len, nums[i]);
B[pos] = nums[i];
}
}
return len;
}
int biSearch(int B[], int length, int ob) {
int l = 0;
int r = length-1;
int mid;
while (l <= r) {
mid = l + (r-l)/2;
if (B[mid] > ob) {
r = mid-1;
}
else if(B[mid] < ob) {
l = mid+1;
}
else {
return mid;
}
}
return l;
}