Middle-题目33: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?
题目大意:
给出一个数组,求最长递增子序列的长度。
你的算法必须达到 On2 的复杂度。进一步,你能提高到O(nlogn)吗?
题目分析:
(1) 朴素解法:暴力分析每一个子列,看看是不是递增的。复杂度是 O(2n) ,忽略。
(2) On2 解法(DP):
记dp[i]为以i为结尾的最长递增子列长度,则有如下转移方程:
dp[i]=max(dp[j])+1 ,其中 j<i ,且 nums[j]<nums[i]
因为计算dp[i]要遍历所有i前面的数,故复杂度 O(n2)
(3) O(nlogn)解法:再增加一个辅助数组B,记B[dp[j]]=a[j].即存储长度为dp[j]的子序列的最后一个元素。这样在从前面的dp[0]~dp[n-1]推dp[n]的时候,可以使用二分查找找到满足 j<i B[dp[j]]=a[j]<a[i] 的最大j值,并置 B[dp[j]+1]=a[i] .(算法思路和源码摘自http://www.cnblogs.com/lonelycatcher/archive/2011/07/28/2119123.html
源码:(language:java)
O(n2)解法:

public class Solution {
    public int lengthOfLIS(int[] nums) {
        if(nums.length<=1)
            return nums.length;
        int[] dp=new int[nums.length];
        dp[0]=1;
        int maxLIS=1;
        for(int i=1;i<nums.length;i++) {
            int maxj=0;
            for(int j=0;j<i;j++) {
                if(dp[j]>maxj && nums[j]<nums[i])
                    maxj=dp[j];
            }
            dp[i]=maxj+1;
            if(dp[i]>maxLIS)
                maxLIS=dp[i];       
}
        return maxLIS;
    }
}

O(nlogn)解法:

public class Solution {
    public int lengthOfLIS(int[] nums) {
        int n = nums.length;
        if(n==0)
            return 0;
        int[] B = new int[n+1];//数组B;
        B[0]=-10000;//把B[0]设为最小,假设任何输入都大于-10000;
        B[1]=nums[0];//初始时,最大递增子序列长度为1的最末元素为a1
        int Len = 1;//Len为当前最大递增子序列长度,初始化为1;
        int p,r,m;//p,r,m分别为二分查找的上界,下界和中点;
        for(int i = 1;i<n;i++) {
            p=0;r=Len;
            while(p<=r)//二分查找最末元素小于ai+1的长度最大的最大递增子序列;
            {
               m = (p+r)/2;
               if(B[m]<nums[i]) p = m+1;
               else r = m-1;
            }
            B[p] = nums[i];//将长度为p的最大递增子序列的当前最末元素置为ai+1;
            if(p>Len) Len++;//更新当前最大递增子序列长度;


        }
        return Len;
    }
}

成绩:
O(n2)解法:42ms,beats 15.71%,众数1ms,13.76%
O(nlogn)解法:2ms,beats 78.15%
Cmershen的碎碎念:
最长递增子序列问题是一个

十分十分十分经典的DP问题

,也是各公司经常用来面试的热门题,关于这个问题的详细讨论可见 joylnwang大神的博客,这篇文章中这个问题进行了比较深入的研究。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值