class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet();
        for (int i : nums) set.add(i);
        int max = 0;
        for (int num : set) {
            if (set.contains(num - 1)) continue; // 上一个数存在,说明当前数不是连续片段的开头
            int cur = num; // 当前数
            int curLen = 0; // 当前长度
            // HashSet加速查找下一个数是否存在,更新最大长度
            while (set.contains(cur++)) {
                curLen++;
                max = Math.max(max, curLen);
            }
        }
        return max;
    }
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐