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();
        }
    };
    
  • 相关阅读:
    单元测试利器 JUnit 4 Mr
    firefox插件介绍 Mr
    js函数使用技巧集合 Mr
    单点登录
    2.SilverLight动态加载控件
    3.如何获取动态生成的SL控件的NAME值(一)
    ASP.Net中控件的EnableViewState属性 【转】
    三种在ASP.NET中重写URL的方法
    SQLHelper.cs
    c# IS与AS的使用方法
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10061052.html
Copyright © 2011-2022 走看看