LeetCode 128: Longest Consecutive Sequence

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 128: Longest Consecutive Sequence相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 128. Longest Consecutive Sequence

Leetcode(128) Longest Consecutive Sequence

LeetCode128 Longest Consecutive Sequence

128. Longest Consecutive Sequence(leetcode)

Leetcode128. Longest Consecutive Sequence

[LeetCode] 128. Longest Consecutive Sequence