HASHING

最长连续序列

中等#128时间 O(n),平均空间 O(n)力扣原题 ↗

题目

在无序整数数组中找到数值连续的最长序列长度。元素不需要在原数组中相邻,要求平均时间复杂度为 O(n)。

示例输入nums = [100,4,200,1,3,2]
示例输出4

思路

先用集合去重。只从没有前驱 x−1 的数开始向右延伸,这样每段连续序列只被扫描一次。

每一步都成立

只有序列起点才能触发扩展,每个不同的数至多参与一次扩展。

看它一步步执行

用的是题目示例
数组 / nums步骤 1
执行状态
这次的结果播放到最后查看

Solution.java参考解法 · 高亮的是正在执行的行
1class Solution {2    public int longestConsecutive(int[] nums) {3        Set<Integer> set = new HashSet<>();4        for (int x : nums) set.add(x);5        int best = 0;6        for (int x : set) {7            if (set.contains(x - 1)) continue;8            int end = x;9            while (set.contains(end + 1)) end++;10            best = Math.max(best, end - x + 1);11        }12        return best;13    }14}
← → 单步 · 空格 播放
↑↓ 选择↵ 打开Pagefind 全文检索