[LeetCode] Longest Increasing Subsequence

本文介绍了一种寻找数组中最长递增子序列长度的方法,提供了两种不同时间复杂度的解决方案,分别是O(n^2)的传统算法和优化后的O(n log n)算法,并通过实例详细解释了优化算法的工作原理。

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,最后将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;
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值