class Solution {
    public int longestConsecutive(int[] nums) {
        if (nums.length < 2) {
            return nums.length;
        }
        
        Set<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }
           
        int length = 1;
        while (!set.isEmpty()) {
            int current = set.iterator().next();
            int left = current;
            int right = current;
            set.remove(current);
            while (set.contains(left - 1)) {
                set.remove(left);
                left--;
            }
            while (set.contains(right + 1)) {
                set.remove(right);
                right++;
            }
            length = Math.max(right - left + 1, length);
        }
        
        return length;
    }
}

 

posted on 2017-08-30 13:23  keepshuatishuati  阅读(90)  评论(0编辑  收藏  举报