leetcode 300.Longest Increasing Subsequence

题目描述:
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?

简单来说,题目要求找到一个数组的最大的上升子串,注意子串的意思说明在数组的子串不一定要连续,可以中间间隔数字,但要保证必须是上升的子串。
这题明显是动态规划。
初始状态:dp[0]=1明显起码有一个数字
状态转移方程:本人最早的想法是:dp[j]=dp[i]+1(if j>i and data[j]>data[i]),可是很明显的在出现数组中突然有变小的数字的时候出现了问题,后来思考的时候,发现dp[j]应该基于前面最好情况下才可以引出dp[i]的值,所以正确的状态转移方程为:
dp[j]=max(da[i])+1(if j>I and data[j]>data[i])
正常情况下,找到max值需要O(n).然后遍历整个data数组需要O(n),那么总的时间为O(n 2 ).(这个复杂度的代码比较简单,暂时不贴了)
那么可以优化的地方就是找到这个max值,用二分查找或者利用STL的lower_bound可以在O(logn)找到max值。
具体代码(经过优化)如下图所示:

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        vector<int> res;
        for(int i=0;i<nums.size();++i)
        {
            //题目要求构建一个完整序列
            //lower_bound即找到第一个大于等于nums[i]的值
            auto it=std::lower_bound(res.begin(),res.end(),nums[i]);
            //如果it==res.end(),说明nums[i]最大,即直接添在后面
            if(it==res.end()) res.push_back(nums[i]);
            //如果不是的话,则添加在第一个大于等于nums[i]的位置上
            else *it=nums[i];
        }
        return res.size();
    }
};

找到这样一个适合的递增序列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值