您的位置:首页 > 产品设计 > UI/UE

Middle-题目33:300. Longest Increasing Subsequence

2016-05-31 15:55 381 查看
题目原文:

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(n2)的复杂度。进一步,你能提高到O(nlogn)吗?

题目分析:

(1) 朴素解法:暴力分析每一个子列,看看是不是递增的。复杂度是O(2n),忽略。

(2) O(n2)解法(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
的时候,可以使用二分查找找到满足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大神的博客,这篇文章中这个问题进行了比较深入的研究。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  matrix 算法