Given an integer array nums
, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7]
is a subsequence of the array [0,3,1,6,2,2,7]
.
Solution
很直接的 \(DP\) 复杂度为 \(O(N^2)\), 即设 \(dp[i]\) 表示以 \(i\) 结尾序列的答案,那么转移为:
\[dp[i]=\max(dp[i], dp[j]+1), \ j< i \]且条件是 \(nums[j]<nums[i]\)
考虑如何变成 \(O(N\log N)\) 的做法,每次当下一个数比当前列表中最后一个大时,那么直接加在后面;否则利用 \(lower\_bound\) 进行替换,因为我们只关心最大的长度
点击查看代码
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len=0;
for(auto ele:nums){
if(len==0 || nums[len-1]<ele){
nums[len] = ele;len++;
}
else {
*lower_bound(nums.begin(), nums.begin()+len, ele)=ele;
}
}
return len;
}
};