码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 128: Longest Consecutive Sequence

时间:2017-08-30 14:14:00      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:long   add   math   iterator   div   sequence   contain   tco   log   

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

 

LeetCode 128: Longest Consecutive Sequence

标签:long   add   math   iterator   div   sequence   contain   tco   log   

原文地址:http://www.cnblogs.com/shuashuashua/p/7452650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!