Longest Increasing Subsequence My Submissions Question
Total Accepted: 6296 Total Submissions: 20294 Difficulty: Medium
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?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Show Tags
一道特别经典的题目,最长递增子序列,可以利用二分查找做优化
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len = nums.size();
if(!len) return 0;
int ans = 0;
vector<int> res(len + 1,INT_MAX);
res[0] = nums[0];
for(int i = 1;i <= len - 1;++i){
int j = find(res,i,nums[i]);
res[j] = nums[i];
}
for(auto i : res){
if(i < INT_MAX) ++ans;
}
return ans;
}
private:
int find(const vector<int>& vi,int len,int target){//在vi中找到某个数刚好大于或者等于target,返回这个数的下标
int l = 0;
int r = len - 1;
int mid;
while(l < r - 1){
mid = l + (r - l) / 2;
if(vi[mid] < target){
l = mid + 1;
}
else if(vi[mid] > target){
r = mid;
}
else return mid;
}
if(vi[l] >= target) return l;//大于等于
else if(vi[r] >= target) return r;//注意这里是大于等于
else return len;
}
};