zoukankan      html  css  js  c++  java
  • 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?

    分析

    这道题先用时间复杂度为O(n^2)的做法来做,dp[i] 表示以nums[i]为结尾的最大非递减子列长度,状态转移方程 if(nums[i]>nums[j]) dp[i]=max(dp[i] ,dp[j]+1), 用maxn记录最大值即可。

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

    继续分析
    可以用stl里的lower_bound写出时间复杂度为O(n*lg(n) )的算法,

    class Solution {
    public:
        int lengthOfLIS(vector<int>& nums) {
        vector<int> res;
        for(int i=0; i<nums.size(); i++) {
            auto it = std::lower_bound(res.begin(), res.end(), nums[i]);
            if(it==res.end()) res.push_back(nums[i]);
            else *it = nums[i];
        }
        return res.size();
        }
    };
    
  • 相关阅读:
    冒泡排序
    快速排序
    玩转git版本控制软件
    django内容总结
    ajax图片上传功能
    随机验证码
    制作博客系统
    django自带的用户认证和form表单功能
    COOKIE 与 SESSION
    Ajax知识
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061052.html
Copyright © 2011-2022 走看看