*LeetCode-Longest Increasing Subsequence

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;
    }
}


你可能感兴趣的:(*LeetCode-Longest Increasing Subsequence)