给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n)
的算法解决此问题。
方法思路
- 哈希集合存储元素:将所有数字存入集合(
Set
),以便快速查询是否存在。 - 识别序列起点:遍历集合中的每个数字,若当前数字的前一个数不在集合中,则当前数字视为连续序列的起点。
- 扩展连续序列:从起点开始,依次检查后续数字是否存在,统计连续序列长度。
- 更新最大长度:每次发现更长的序列时更新最大值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
function str1(nums){
//先对数据存储
const numSet = new Set(nums);
let maxLength =0;
for (const num of numSet) {
// 只有当当前数是连续序列的起点时(即前一个数不存在),才进行处理,这个很关键
if(!numSet.has(num-1)){
let cruu =num //如果当前值没有,就从它开始,主要确定开始起始第一个值
let length =1 //记录长度1
向后查找连续的数字
while(numSet.has(cruu+1)){
//如果有下一个
length++;
cruu++;
}
maxLength=Math.max(maxLength, length)
}
}
return maxLength
}
console.log(str1([8,2,4,5,3,4,5,2,1]))
function longestConsecutive(nums) {
let maxLength = 0;
let numSet =new Set(nums)//不需要排序 只需要去重即可
for (const num of numSet) {//循环set
// 只有当当前数是连续序列的起点时(即前一个数不存在),才进行处理
if (!numSet.has(num - 1)) {
let currentNum = num;
let currentLength = 1;
// 向后查找连续的数字
while (numSet.has(currentNum + 1)) {
currentNum++;
currentLength++;
}
// 这一轮完了 更新最大长度
maxLength = Math.max(maxLength, currentLength);
}
}
return maxLength;
}
console.log(longestConsecutive([8, 2, 4, 5, 3, 2, 1]))
</script>
</html>
代码解释
- 集合初始化:
numSet
存储所有唯一数字,确保每个数字只处理一次。 - 遍历集合元素:使用
for...of
循环遍历集合中的每个数字。 - 检查序列起点:若当前数字的前一个数不在集合中,说明它是某个连续序列的起点。
- 扩展序列:从起点开始,通过
while
循环不断检查下一个数字是否存在,计算当前连续序列的长度。 - 更新最大值:每次循环结束后,比较并更新最长连续序列的长度。
此方法的时间复杂度为O(n),因为每个元素最多被访问两次(一次加入集合,一次作为序列的一部分处理),确保了线性时间复杂度。