

nums,返回最长连续元素序列的长度,并且算法必须运行在 O(n) 时间内。Set,再只从连续段的起点向右扩展。如果 num - 1 也在集合里,说明 num 不是起点,直接跳过;只有起点才进入 while 扩展。这样每段连续序列只会被完整扫描一次。function longestConsecutive(nums) {
const set = new Set(nums);
let best = 0;
for (const num of set) {
if (set.has(num - 1)) continue;
let current = num;
let length = 1;
while (set.has(current + 1)) {
current++;
length++;
}
best = Math.max(best, length);
}
return best;
}O(n):每个数字只承担常数次集合查询。空间复杂度是 O(n):Set 需要存下去重后的数字。This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.