*LeetCode-Longest Increasing Subsequence

28 篇文章 0 订阅

dp基本的dp o(n方)每次扫这个数字所有前面的有几个小于他的 然后更新这个位置为止的longest 这个数字完成之后 就更新global max

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

还有binary search的dp  o(nlogn)

java自带的arrays binary search返回target index 假如target没找到 就返回 - (insertion place) - 1

所以keep了一个subarray就是result array 然后知道他的长度, 假如插入的位置是最后 length ++

否则就直接改变那个位置的数字 长度不变 这样有助于把整个subarray每个位置放到最小

public class Solution {
    public int lengthOfLIS(int[] nums) {
        if ( nums == null || nums.length == 0 )
            return 0;
        int [] res = new int [ nums.length ];
        res [ 0 ] = nums [ 0 ];
        int len = 1;
        for ( int i = 1; i < nums.length; i ++ ){
            int index = Arrays.binarySearch( res, 0, len, nums [ i ] );
            if ( index < 0 )
                index = - ( index + 1 );
            res[ index ] = nums [ i ];
            if ( index == len )
                len ++;
        }
        return len;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值