【leetcode】300. Longest Increasin
2019-05-13 本文已影响0人
邓泽军_3679
1、题目描述
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
- 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?
2、问题描述:
- 给一个数组,从这个数组中找到一个最长的上升子序列,并返回长度。
3、问题关键:
- 1.DP:
状态表示:f[i]表示以第i个元素结尾的最长的子序列。
状态转移:f[i] = max(f[i], f[j] + 1),
如果第j个元素比 第i个元素小的话。
- 根据长度为i的子序列的最小后缀。(二分)
长度为i的最小元素,一定比长度为i+1的结束的元素 小。可以通过更新长度为i个元素的结束的最小值,就可以得到最长的子序列。
4、C++代码:
算法1:DP
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> f(n, 0);
for (int i = 0; i < n; i ++) {
f[i] = 1;
for (int j = 0; j < i; j ++)
if (nums[j] < nums[i])
f[i] = max(f[i], f[j] + 1);
}
int res = 0;
for (int i = 0; i < n; i ++) res = max(res, f[i]);
return res;
}
};
算法2:(二分)
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> q(n);
int t = 0;
for (auto x : nums) {
if (!t || x > q[t - 1]) q[t ++] = x;
else {
int l = 0, r = t - 1;
while(l < r) {
int mid = l + r >> 1;
if (q[mid] >= x) r = mid;
else l = mid + 1;
}
q[r] = x;
}
}
return t;
}
};