Algorithms first

最长连续序列 · 交互式算法学习

找出最长连续整数序列长度。

#128 · 哈希表

最长连续序列

Longest Consecutive Sequence

测试用例nums = [100,4,200,1,3,2]
线性序列3 个关键状态
步骤 1100 是起点,但序列长度 1。best=1
100
0
4
1
200
2
1
3
3
4
2
5
推荐

集合只从序列起点扩展

时间 O(n)空间 O(n)

若 x-1 不在集合,x 才是序列起点,向右连续查找。

1function longestConsecutive(a) {2  const set = new Set(a);3  let best = 0;4  for (const x of set)5    if (!set.has(x - 1)) {6      let y = x;7      while (set.has(y)) y++;8      best = Math.max(best, y - x);9    } return best;10}
多语言参考

Java · C++ · Go

来源 · CC BY-SA 4.0 ↗

这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。

1class Solution {2    public int longestConsecutive(int[] nums) {3        Set<Integer> s = new HashSet<>();4        for (int x : nums) {5            s.add(x);6        }7        int ans = 0;8        Map<Integer, Integer> d = new HashMap<>();9        for (int x : nums) {10            int y = x;11            while (s.contains(y)) {12                s.remove(y++);13            }14            d.put(x, d.getOrDefault(y, 0) + y - x);15            ans = Math.max(ans, d.get(x));16        }17        return ans;18    }19}
交互式算法学习

从执行步骤真正理解 LeetCode 经典 150

本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。

多形态可视化数组、矩阵、DP 表、递归树、树图、链表、栈队列堆、区间和状态机按解法选择。
动画与代码同步当前状态、步骤说明、变量和代码高亮保持一一对应,可逐步播放和回退。
适合面试复习每种方案都给出思路、时间复杂度、空间复杂度、测试用例和 LeetCode 中文原题入口。
AlgoViz Lab

最长连续序列 · 解法对比

找出最长连续整数序列长度。

测试用例
nums = [100,4,200,1,3,2]
题目分类
哈希表
解法对比
2
方案 1

排序后扫描

排序去重后统计连续递增段。

时间
O(n log n)
空间
O(n)
方案 2

集合只从序列起点扩展

若 x-1 不在集合,x 才是序列起点,向右连续查找。

时间
O(n)
空间
O(n)