您的位置:首页 > 产品设计 > UI/UE

*LeetCode-Longest Increasing Subsequence

2015-11-05 04:24 513 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: