Algorithms first
最长连续序列 · 交互式算法学习
找出最长连续整数序列长度。
#128 · 哈希表
最长连续序列
Longest Consecutive Sequence
nums = [100,4,200,1,3,2]线性序列3 个关键状态
步骤 1100 是起点,但序列长度 1。
best=1100
04
1200
21
33
42
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}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
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 同题参考实现。
AlgoViz Lab
最长连续序列 · 解法对比
找出最长连续整数序列长度。
- 测试用例
nums = [100,4,200,1,3,2]- 题目分类
- 哈希表
- 解法对比
- 2
排序后扫描
排序去重后统计连续递增段。
- 时间
O(n log n)- 空间
O(n)
集合只从序列起点扩展
若 x-1 不在集合,x 才是序列起点,向右连续查找。
- 时间
O(n)- 空间
O(n)