给定一个未排序的数组 nums,找出数字连续的最长序列c++
时间: 2025-06-23 13:26:48 AIGC 浏览: 19
### C++算法实现
对于给定的无序整数数组,目标是找出其中最长连续元素序列的长度。此问题可以通过哈希表来高效解决。
为了提高查找效率并减少时间复杂度,可以利用`unordered_set`存储所有元素[^1]。遍历数组中的每一个数字时,在集合中检查该数字是否是一个序列的起点(即前驱不在集合内)。如果是,则继续向后探查后续连续数字,并记录当前已知的最大长度。
下面展示了一个具体的C++代码示例:
```cpp
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
unordered_set<int> num_set(nums.begin(), nums.end());
int maxLength = 0;
for (const auto& num : num_set){
// Check if it's the start of a sequence
if (!num_set.count(num - 1)){
int currentNum = num;
int currentStreak = 1;
while (num_set.count(currentNum + 1)) {
currentNum += 1;
currentStreak += 1;
}
maxLength = max(maxLength, currentStreak);
}
}
return maxLength;
}
// 测试函数
void test() {
vector<int> input = {100, 4, 200, 1, 3, 2};
cout << "The length of the longest consecutive elements sequence is: "
<< longestConsecutive(input) << endl; // 输出应为4
}
```
这段程序首先将输入的数据存入到一个`unordered_set`容器中以便快速访问;接着通过迭代器遍历这个集合里的每一项,当遇到可能是某个序列开头的位置时就尝试构建完整的子串直到无法再接续为止;最后返回所发现的最大连贯片段大小作为最终结果[^2]。
阅读全文
相关推荐




















