时间轴

2025-11-14

init


题目:


用哈希表,虽然是for循环里面一个while,但是整体来看每个元素只访问了一次。

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
#include <vector>
#include <unordered_set>
using std::unordered_set;
using std::vector;

class Solution {
public:
int longestConsecutive(vector<int> &nums)
{
unordered_set<int> uset;
for (int &num : nums) {
uset.insert(num);
}
int longest = 0, curr = 0;
for (auto &num : uset) {
if (!uset.count(num - 1)) {
curr = 1;
while (uset.count(num + curr)) {
curr++;
}
longest = std::max(curr, longest);
}
}
return longest;
}
};