给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
function longestConsecutive(nums: number[]): number {
//哈希 set,核心思路是找序列的起点,往后数能数几个就是其序列长度,仅需遍历一次就能找到长度
let max_length = 0
const set = new Set(nums)
for (const n of set) {
if (set.has(n - 1)) continue;
// 是起点,往后数
let i = 1;
while (set.has(n + i)) {
i++;
}
max_length = Math.max(max_length, i);
}
return max_length
};