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

*LeetCode-Longest Consecutive Sequence

2015-10-07 04:28 501 查看
用了一个hashmap存每个数字到目前为止最长的length 

没加入一个数 看他的n-1和n+1在不在map里面 假如在 那左边数字的value就是n左边有多少个连续数字 不存在左边长度就是0

右边同理 然后length = leftLen + rightLen + 1 放入 

最重要的一步是要push boundary,自己更新之后 最左边和最右边的数字也要更新 以便以后使用

之中keep了一个max

public class Solution {
public int longestConsecutive(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
if ( nums == null || nums.length == 0 )
return 0;
int max = 0;
for ( int n : nums ){
if ( !map.containsKey( n )){
int leftLen = map.containsKey( n - 1) ? map.get( n - 1 ) : 0;
int rightLen = map.containsKey( n + 1 ) ? map.get ( n + 1 ) : 0;
int length = leftLen + rightLen + 1;
max = Math.max ( max, length );
map.put ( n, length );
map.put ( n - leftLen, length );
map.put ( n + rightLen, length );
}
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: