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

[LeetCode] Longest Increasing Subsequence

2017-06-05 06:43 411 查看
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)复杂度实现:

public class Solution {
public int lengthOfLIS(int[] nums) {
if(nums.length==0) return 0;
int[] dp=new int[nums.length];
for(int i=0;i<nums.length;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(dp[j]<dp[i]) dp[i]=Math.max(dp[i],dp[j]+1);
}
}
return dp[dp.length-1];
}


o(nlogn)实现:

public class Solution2 {
//来看一个例子,以序列{6,7,8,9,10,1,2,3,4,5,6}来说明改进算法的步骤:
//程序开始时,最长递增序列长度为1(每个元素都是一个长度为1的递增序列),当处理第2个元素时发现7比最长递增序列6的最大元素还要大,所以将6,7结合生成长度为2的递增序列,说明已经发现了长度为2的递增序列,依次处理,到第5个元素(10),这一过程中B数组的变化过程是
// 6
// 6,7
// 6,7,8
// 6,7,8,9
// 6,7,8,9,10
//开始处理第6个元素是1,查找比1大的最小元素,发现是长度为1的子序列的最大元素6,说明1是最大元素更小的长度为1的递增序列,用1替换6,形成新数组1,7,8,9,10。然后查找比第7个元素(2)大的最小元素,发现7,说明存在长度为2的序列,其末元素2,比7更小,用2替换7,依次执行,直到所有元素处理完毕,生成新的数组1,2,3,4,5,最后将
9887
6加入B数组,形成长度为6的最长递增子序列.
//这一过程中,B数组的变化过程是
// 1,7,8,9,10
// 1,2,8,9,10
// 1,2,3,9,10
// 1,2,3,4,10
// 1,2,3,4,5
// 1,2,3,4,5,6
//当处理第10个元素(5)时,传统算法需要查看9个元素(6,7,8,9,10,1,2,3,4),而改进算法只需要用二分查找数组B中的两个元素(3, 4),可见改进算法还是很阴霸的。
public int lengthOfLIS(int[] nums) {
if(nums.length==0) return 0;
int[] dp=new int[nums.length];
int len=0;
for(int i=0;i<nums.length;i++){
int pos=Arrays.binarySearch(dp,0,len,nums[i]);
if(pos<0) pos=-(pos+1);
dp[pos]=nums[i];
if(pos==len) len++;
}
return len;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: