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.
思路:用哈希表unordered_map<int,bool> umap存储num中的所有数据,并初始化为false。然后顺序读取num,每读到一个数,就在umap的左右两边顺序遍历,查找相邻的连续元素是否出现,若找到,就将其值为true,防止下次重复访问。
代码:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int LongestConsecutive(vector<int>& num)
{
unordered_map<int,bool> umap;
for (int i=0;i<num.size();i++)
{
umap[num[i]] = false;
}
int longest=1;
for (int i=0;i<num.size();i++)
{
if (umap[num[i]])
continue;
umap[num[i]] = true;
int temp=1;
for (int j=num[i]-1;umap.find(j)!=umap.end();j--)
{
umap[j] = true;
temp++;
}
for (int j=num[i]+1;umap.find(j)!=umap.end();j++)
{
umap[j] = true;
temp++;
}
if (temp>longest)
{
longest = temp;
}
}
return longest;
}
int main()
{
int num[]={4,3,6,8,7,9,10,1,12,18,27,26,25,24,23};
int length = sizeof(num)/sizeof(int);
vector<int> vec(num,num+length);
int longest = LongestConsecutive(vec);
cout<<longest<<endl;
return 0;
}