0%

最长连续序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var longestConsecutive = function (nums) {
//nums未排序,找出数字连续的最长序列,要求O(n)
let set = new Set(nums) //数组去重放入set中
let max_len = 0
for (let num of set) {
//遍历集合
let len = 1
// 从中心向两边扩散查找
let left = num - 1,
right = num + 1
while (set.has(left)) {
//找到就删掉,避免重复遍历,导致超时
set.delete(left)
left--
len++
}
while (set.has(right)) {
set.delete(right)
right++
len++
}
max_len = Math.max(len, max_len)
}
return max_len
}