最长连续序列
题目:最长连续序列
给定一个未排序的整数数组nums,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为O(n)的算法解决此问题。
var longestConsecutive = function (nums) {
nums.sort((a, b) => (a - b))
let i = 0, j = 0, len = 0, max = 0
if (nums.length == 1) return 1
while (j < nums.length) {
if (nums[i] + len == nums[j]) {
len++
} else if(nums[i] + len - 1 == nums[j]) {
} else {
i = j
if (len > max) {
max = len
}
len = 1
}
j++
}
if (len > max) {
max = len
}
return max
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
上次更新: 2025/09/05, 8:09:00