算法第八周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; }
相关文章推荐
- 算法第八周Number of Longest Increasing Subsequence[medium]
- 算法系列——Longest Increasing Subsequence
- 673[Medium]: Number of Longest Increasing Subsequence
- lintcode-medium-Longest Increasing Subsequence
- 300.LeetCode Longest Increasing Subsequence(medium)[动态规划]
- Leetcode算法学习日志-673 Number of Longest Increasing Subsequence
- Longest Increasing Subsequence的两种算法
- 【算法】Longest Increasing Subsequence
- Longest Increasing Subsequence (Medium)
- Longest Increasing Subsequence (Medium)
- SRM 626 D1L2:CatchTheBeat,Longest increasing subsequence,O(NlogN) 算法
- DP (7) -- Ones and Zeroes, Longest Increasing Subsequence, Perfect Squares
- Longest Increasing Subsequence
- Leetcode - Longest Increasing Subsequence
- longest increasing subsequence(O(nlogn))
- 最长递增子序列(longest increasing subsequence)
- 最长递增子序列 (LIS) Longest Increasing Subsequence
- 最长递增子序列详解(longest increasing subsequence)
- 最长上升子序列LIS(Longest increasing subsequence)
- LCS (Longest Common Subsequence) 字符串最长公共子串算法