longest-consecutive-sequence
题目描述
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
For example,Given[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.
Your algorithm should run in O(n) complexity.
思路
题目要求线性时间内实现,先排序再查找这种方法被摒弃了
用一个set集合存储数组
对原数组遍历
如果元素在集合中,对其左右两边搜索(比如3, 搜索是否2,1,0….在集合,搜索4,5,6,……是否在集合中,集合必须删除访问过的节点
返回最大连续长度
代码
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_set<int> myset(num.begin(),num.end());
int res=1;
for(int current:num)
{
if(myset.find(current)==myset.end()) continue;
myset.erase(current);
int prev=current-1,post=current+1;
while(myset.find(prev)!=myset.end())
{
myset.erase(prev--);
}
while(myset.find(post)!=myset.end())
{
myset.erase(post++);
}
res=max(res,post-prev-1);
}
return res;
}
};