300. Longest Increasing Subsequence

本文介绍了两种求解最长递增子序列(LIS)问题的算法:常规动态规划方法和优化后的O(n log n)算法。常规方法通过维护一个dp数组记录到每个元素为止的最长递增子序列长度;优化方法则利用二分查找减少时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.




 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值