您的位置:首页 > 产品设计 > UI/UE

算法第八周Longest Increasing Subsequence[medium]

2017-10-25 20:50 393 查看

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]) {

4000
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: