时间复杂度:O(nlogn)
二分查找优化:
b[j] : stores length is j (f value is j), smallest ending value.
O(n^2) 的写法是用动态规划,f[i]里存储数组索引为i时的最长上升子序列的长度。而在用二分查找时,设置b[k]来存储当f[i]的值是j时(即最长上升子序列的长度为j时),这个序列的最后一个值(最小的)。遍历n次,每次都二分查找到b[k]里最大那个小于nums[i]的数字, 然后将b[j+1] 替换为 nums[i].
class Solution { public: int lengthOfLIS(vector<int>& nums) { int n = nums.size(); if(n==0) return 0; int b[n+1]; //b[i]: when f value is i, smallest nums value(ending value) int top=0; //top一定要初始化 否则会指针溢出 b[0] = INT_MIN; //O(n) for(int i=0; i<n; i++){ // b[0]...b[top] find the last value b[j] which is smaller than nums[i] int start = 0, stop = top; int mid, j; //O(logn) while(start<= stop){ mid = (start + stop)/2; if(b[mid]<nums[i]){ j = mid; //找到一个 先存下来 start = mid+1; //然后在后面找,因为要找最后一个比nums[i]小的 } else stop = mid-1; } b[j+1] = nums[i]; //f[i] = j+1 if(j+1 > top) top = j+1; //更新top } //b[0]...b[top] //b[top] stores the smallest ending value for an increasing sequence with length top return top; //top的长度就是f[i]的值,即LIS } };
(DP+二分查找) leetcode 300. Longest Increasing Subsequence
原文:https://www.cnblogs.com/Bella2017/p/11358232.html