the normal way:
public class Solution {
public int lengthOfLIS(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int[] dp = new int[nums.length];
Arrays.fill(dp,1);
int ret = 1;
for(int i = 1; i<nums.length; i++){
int max = 1;
for(int j = 0; j<i;j++){
if(nums[i]>nums[j]){
max = Math.max(dp[j]+1, max);
}
}
dp[i] = max;
ret = Math.max(ret,max);
}
return ret;
}
}dp[i] means the LIS from nums[0] to nums[i]. when nums[i+1] comes in, we just need to check dp[0] -> dp[i], find the max dp[k] where nums[k] < nums[i+1]
then dp[i+1] = dp[k] + 1.
the O(nlgn) way:
public class Solution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
Arrays.fill(dp,Integer.MAX_VALUE);
for(int i : nums){
int index = binarySearch(dp,i);
if(index < 0){
dp[-(index + 1)] = i;
}
}
for(int i = dp.length - 1; i>=0; i--){
if(dp[i] != Integer.MAX_VALUE){
return i+1;
}
}
return 0;
}
int binarySearch(int[] nums, int i){
int start = 0;
int end = nums.length;
while(start<end){
int midIndex = start + (end - start)/2;
int mid = nums[midIndex];
if(mid < i){
start = midIndex + 1;
}
else if(mid == i){
return midIndex;
}
else{
end = midIndex;
}
}
return -start - 1;
}
}we could maintain an array of the current LIS while i increase, when a new element nums[i] comes, we should replace first element larger then nums[i]. if no element larger than nums[i], we just append it to the last of the LIS.
for example,
1,3,4,2,0,6,3
1
1,3
1,3,4
1,2,4
0,2,4
0,2,4,6
0,2,3,6
Anyway the longest index ever reached in the dp array will be the length of LIS. the substitution ensures the current LIS is always optimal.
PS, we could use the built-in Arrays.binarySearch to achieve the same result.
本文介绍了两种求解最长递增子序列(LIS)问题的算法:常规动态规划方法和优化后的O(n log n)算法。常规方法通过维护一个dp数组记录到每个元素为止的最长递增子序列长度;优化方法则利用二分查找减少时间复杂度。
4339

被折叠的 条评论
为什么被折叠?



