题目:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
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.
代码如下:
int longestConsecutive(vector<int> &num) {
int n=num.size();
set<int> map;
for(int i=0;i<n;i++)
{
map.insert(num[i]);
}
vector<int> tmp;
for(set<int>::iterator i=map.begin();i!=map.end();i++)
{
tmp.push_back(*i);
}
if(tmp.size()==1)return 1;
int len=0;
for(int j=1;j<tmp.size();j++)
{
int t=1;
while(j<tmp.size()&&tmp[j]-tmp[j-1]==1)
{
j++;
t++;
}
if(t>len)len=t;
}
return len;
}