最长上升子序列

最长上升子序列

在这里插入图片描述
给定一个无序的整数数组,找到其中最长上升子序列的长度。

package factory;

/**
 * @Description: 最长上升子序列
 * https://leetcode-cn.com/explore/interview/card/top-interview-quesitons-in-2018/272/dynamic-programming/1179/
 * @Author: Jaryn
 * @Date: 2019/12/14 14:30
 */
public class LengthOfLIS {

    public static void main(String[] args) {
        int[] nums = new int[]{1,3,6,7,9,4,10,5,6};
        System.out.println(lengthOfLIS(nums));
    }

    /**
     * 复杂度太高
     * 15 ms 56.7%
     * 思路是保存一个数组,保存比他小的数的数量,每一个往前遍历比较。
     * 优化的思路是一边遍历一边保持一个有序的数组,然后根据二分查找找出这个数该有的位置。
     * @param nums
     * @return
     */
    public static int lengthOfLIS(int[] nums) {
        int len = nums.length;
        if (len == 0) {
            return 0;
        }
        int[] dt = new int[len];
        dt[0] = 1;
        int max = 1;
        for(int i=1; i<len; i++) {
            int val = nums[i];
            int tempmax = Integer.MIN_VALUE;
            for(int j = i -1; j >=0; j--) {
                if(nums[j] < nums[i] && dt[j] > tempmax) {
                    tempmax = dt[j];
                    dt[i] = dt[j] + 1;

                }
            }
            if(dt[i] == 0) {
                dt[i] = 1;
            }
            if(dt[i] > max) {
                max = dt[i];
            }
        }
        return max;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值