# 最长连续序列
给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n)
的算法解决此问题。
示例 1:
输入:nums = [100,4,200,1,3,2]
输出:4
解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
示例 2:
输入:nums = [0,3,7,2,5,8,4,6,0,1]
输出:9
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
vector vec = {0, 3, 7, 2, 5, 8, 4, 6, 0, 1};
res = sol.longestSequence(vec);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int longestConsecutive(vector &nums)
{
unordered_set hash;
for (const int &num : nums)
{
hash.insert(num);
}
int ans = 0;
while (!hash.empty())
{
int cur = *(hash.begin());
hash.erase(cur);
int next = cur + 1, prev = cur - 1;
while (hash.count(next))
{
hash.erase(next++);
}
while (hash.count(prev))
{
hash.erase(prev--);
}
ans = max(ans, next - prev);
}
return ans;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int longestConsecutive(vector &nums)
{
unordered_map mp;
int l = 0, r = 0, res = 0, len = 0;
for (int num : nums)
{
if (!mp[num])
{
l = mp[num - 1];
r = mp[num + 1];
len = l + r + 1;
res = max(res, len);
mp[num] = len;
mp[num - l] = len;
mp[num + r] = len;
}
}
return res;
}
};
```
### B
```cpp
class Solution
{
struct DisJointSet
{
vector _id;
vector _size;
int max_size;
int _count;
DisJointSet(int Num)
{
for (int i = 0; i < Num; i++)
{
_id.emplace_back(i);
_size.emplace_back(1);
}
_count = Num;
max_size = 1;
}
int find_(int p)
{
while (p != _id[p])
{
_id[p] = _id[_id[p]];
p = _id[p];
}
return p;
}
void _union(int p, int q)
{
int i = find_(p);
int j = find_(q);
if (i == j)
return;
if (_size[i] > _size[j])
{
_id[j] = i;
_size[i] += _size[j];
max_size = max(max_size, _size[i]);
}
else
{
_id[i] = j;
_size[j] += _size[i];
max_size = max(max_size, _size[j]);
}
_count--;
}
};
public:
int longestConsecutive(vector &nums)
{
if (nums.size() == 0)
return 0;
DisJointSet disJointSet(nums.size());
unordered_set nums_set;
unordered_map nums_disJointSetID_map;
for (int i = 0; i < nums.size(); i++)
{
if (nums_set.find(nums[i]) != nums_set.end())
continue;
nums_set.insert(nums[i]);
nums_disJointSetID_map[nums[i]] = i;
if (nums_set.find(nums[i] - 1) != nums_set.end())
{
disJointSet._union(nums_disJointSetID_map[nums[i]], nums_disJointSetID_map[nums[i] - 1]);
}
if (nums_set.find(nums[i] + 1) != nums_set.end())
{
disJointSet._union(nums_disJointSetID_map[nums[i]], nums_disJointSetID_map[nums[i] + 1]);
}
}
return disJointSet.max_size;
}
};
```
### C
```cpp
class Solution
{
public:
int longestConsecutive(vector &vec)
{
set s;
for (int elem : vec)
s.insert(elem);
int longest = 0;
int cnt = 1;
for (auto e : s)
{
if (s.find(e + 1) != s.end())
{
cnt++;
}
else
{
cnt = 1;
}
longest = max(longest, cnt);
}
return longest;
}
};
```