128 Longest Consecutive Sequence

public class Solution {
    public int longestConsecutive(int[] nums) {
        HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>();
        for (int i : nums) {
            hs.put(i, 0);
        }
        int max = 1;
        
        for (int i : nums) {
            if (hs.get(i) == 1) {
                continue;
            }
            int temp = i;
            int currentMax = 1;
            while (hs.containsKey(temp+1)) {
                currentMax++;
                temp++;
                hs.put(temp, 1);
            }
            
            temp = i;
            while (hs.containsKey(temp-1)) {
                currentMax++;
                temp--;
                hs.put(temp, 1);
            }
            max = Math.max(currentMax, max);
        }
        return max;
    }
}

当成图想,对每一个i向两边扫, 用hashMap

参考九章答案,以及http://blog.csdn.net/linhuanmars/article/details/22964467

posted on 2015-05-29 09:55  kikiUr  阅读(152)  评论(0编辑  收藏  举报