[C++] LeetCode 300. 最长上升子序列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lv1224/article/details/81712742

题目

给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例:

输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。

说明:
可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
你算法的时间复杂度应该为 O(n2)
进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?

方法一 动态规划

这题用动态规划比较直接,开一个数组,保存以当前元素为结尾的最长递增序列

代码

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int maxres=1;
        int n=nums.size();
        if(n==0) return 0;
        vector<int> res(n,1);
        for(int i=1;i<n;i++){
            for(int j=0;j<i;j++){
                if(nums[i]>nums[j]){
                    res[i]=max(res[i],res[j]+1);
                }
            }
            maxres=max(maxres,res[i]);
        }
        return maxres;
    }
};

方法二 二分查找

开一个数组,用于维护一个递增的序列,通过二分查找找到当前元素在该数组中的插入位置,插入元素。那么最终这个数组的长度即为最长递增序列。但是这个数组不是所求的递增序列。

代码

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

猜你喜欢

转载自blog.csdn.net/lv1224/article/details/81712742