LeetCode – LongestIncreasing Subsequence (Java)

本文介绍两种求解最长递增子序列长度的方法:朴素解法和二分搜索解法。朴素解法通过动态规划思想,遍历数组比较每个元素,得到最长递增子序列的长度;二分搜索解法则通过维护一个列表来存储递增子序列,并利用二分搜索更新列表,实现更高效的查找。

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


Given an unsorted array of integers, find the length of longestincreasing subsequence.

For example, given [10, 9, 2, 5, 3, 7, 101, 18], the longestincreasing subsequence is [2, 3, 7, 101]. Therefore the length is 4.

Java Solution 1 - Naive

Letmax[i] represent the length of the longest increasing subsequence so far.
If any element before i is smaller than nums[i], then max[i] = max(max[i],max[j]+1).

Here is an example:

public int lengthOfLIS(int[] nums) {
    if(nums==null || nums.length==0)
        return 0;
 
    int[] max = new int[nums.length];
 
    for(int i=0; i<nums.length; i++){
        max[i]=1;
        for(int j=0; j<i;j++){
            if(nums[i]>nums[j]){
                max[i]=Math.max(max[i], max[j]+1);
            }
        }
    }
 
    int result = 0;
    for(int i=0; i<max.length; i++){
        if(max[i]>result)
            result = max[i];
    }
    return result;
}

Java Solution 2 - Binary Search

We can put the increasing sequence in a list.

for each num in nums
     if(list.size()==0)
          add num to list
     else if(num > last element in list)
          add num to list
     else 
          replace the element in the list which is the smallest but bigger than num

 

public int lengthOfLIS(int[] nums) {
    if(nums==null || nums.length==0)
        return 0;
 
    ArrayList<Integer> list = new ArrayList<Integer>(); 
 
    for(int num: nums){
        if(list.size()==0 || num>list.get(list.size()-1)){
            list.add(num);
        }else{
            int i=0; 
            int j=list.size()-1;
 
            while(i<j){
                int mid = (i+j)/2;
                if(list.get(mid) < num){
                    i=mid+1;
                }else{
                    j=mid;
                }
            }
 
            list.set(j, num);
        }
    }
 
    return list.size();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值