leetcode128:最长连续序列

题目链接

leetcode

题目描述

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
设计并实现时间复杂度为 O(n) 的算法解决此问题。

C++ 代码

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <vector>
#include <unordered_set>
#include <unordered_map>
using namespace std;

/*
哈希集合

时间复杂度:O(n)
其中 n 为数组的长度。
空间复杂度:O(n)
哈希表存储数组。
*/
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> set;
for (const int& num : nums) {
set.insert(num);
}

int res = 0;
for (const int& num : set) {
// num 是连续子序列的第一个
if (!set.count(num-1)) {
int curNum = num;
int curLength = 1;

// 开始向上计算连续子序列的长度
while (set.count(curNum+1)) {
curNum++;
curLength++;
set.erase(curNum);
}

// 更新最长连续序列的长度
res = max(res, curLength);
}
}

return res;
}
};

// 辅助函数:打印数组
void printArray(const vector<int>& nums) {
cout << "[";
for (size_t i = 0; i < nums.size(); i++) {
cout << nums[i];
if (i != nums.size() - 1) cout << ",";
}
cout << "]";
}

int main() {
Solution solution;
vector<vector<int>> nums_cases = {
{100,4,200,1,3,2},
{0,3,7,2,5,8,4,6,0,1},
{1,0,1,2}
};

for (auto& nums : nums_cases) {
int result = solution.longestConsecutive(nums);

cout << "Input: ";
printArray(nums);
cout << endl;
cout << "Output: " << result << endl;
}

return 0;
}

leetcode128:最长连续序列
https://lcf163.github.io/2024/04/07/leetcode128:最长连续序列/
作者
乘风的小站
发布于
2024年4月7日
许可协议