128. 最长连续序列

184 阅读1分钟

题目

image.png

方法

image.png

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int x : nums) {
            set.add(x);
        }
        int res = 0;
        for (int x : nums) {
            if (!set.contains(x - 1)) {// 优化
                int count = 0, i = 0;
                while (set.contains(x + i)) {
                    count++;
                    i++;
                }
                res = Math.max(res, count);
            }
        }
        return res;
    }
}