最长连续序列

最长连续序列题目的哈希集合解法与连续起点判断思路

#type / howto #status / evergreen #resource / algorithm #source / leetcode #ds / hash

[!info] related notes

最长连续序列

分析

关键在于快速找到连续序列的最小值,然后在遍历完整得到 长度。 然后在 得到的长度中 取最大。

function longest(nums) {
	const st = new Set(nums);
	let ans = 0;
	let (num of st) {
		if (st.has(num-1)) {
			continue;
		}
		// 当前连续序列最小值 为 num, 然后在剩余集合中找 num + 1,看看是否存在连续序列
		let next = num + 1;
		// 要用 while 循环一直找到最终值
		while (st.has(next)) {
			next++;
		}
		ans = Math.max(ans, next - num)
	}
	return ans;
}
创建于 2026/3/3 更新于 2026/5/27