[leetcode]300. Longest Increasing Subsequence

来源:互联网 发布:js兼容性注释 编辑:程序博客网 时间:2024/06/04 00:30

题目链接:https://leetcode.com/problems/longest-increasing-subsequence/#/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?

方法一(超时):解法参考

class Solution{public:    int lengthOfLIS(vector<int>& nums)    {        int maxLength=0;        for(int i=1;i<=nums.size();i++)        {            vector<int> tmp(i,INT_MAX);            for(int j=0;j<nums.size();j++)            {                for(int k=0;k<i;k++)                {                    if(nums[j]<=tmp[k])                    {                        tmp[k]=nums[j];                        break;                    }                }            }            int i=0;            while(tmp[i]!=INT_MAX && i<tmp.size())            {                i++;            }            if(i>maxLength)                maxLength=i;        }        return maxLength;    }};

方法二:

动态规划:

class Solution{public:    int lengthOfLIS(vector<int>& nums)    {        int maxLength=1;        if(nums.size()==0)            return 0;        vector<int> res(nums.size(),1);//vector[i]表示前i个数中具有的最大连续长度        for(int i=0;i<nums.size();i++)        {            for(int j=i+1;j<nums.size();j++)            {                if(nums[j]>nums[i])                {                    res[j]=max(res[j],res[i]+1);                    if(res[j]>maxLength)                        maxLength=res[j];                }            }        }        return maxLength;    }};

方法三:

思路:新建一个数组res,把nums[ 0 ]放进数组,随后遍历nums[ 1 ] - nums[ nums.size()-1 ],如果nums[ i ]比res.back()大,则把nums[ i ]放进res的后面,否则,把nums[ i ]替换res中第一个比nums[ i ]大的数,可参考

举例:原序列为1,5,8,3,6,7

开始1,5,8相继加入数组V,此时读到3,用3替换5,得到1,3,8;

 再读6,用6替换8,得到1,3,6;

再读7,得到最终数组为1,3,6,7。最长递增子序列为长度

public:    int lengthOfLIS(vector<int>& nums)    {        if(nums.size()==0)            return 0;        vector<int> res;        res.push_back(nums[0]);        for(int i=1;i<nums.size();i++)        {            if(nums[i]>res.back())                res.push_back(nums[i]);            else                *lower_bound(res.begin(),res.end(),nums[i])=nums[i];        }        return res.size();    }};


1 0