Problem:
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.
用一个哈希表记录每个元素是否用过,另外,对每个元素,以该元素为中心向两边扩张即可方便地找出最长的长度。
class Solution {
public:
int longestConsecutive(vector<int> const& num)
{
hash_map<int,bool>hashlist;
for (int i = 0; i < num.size(); i++)
{
hashlist[num[i]]=true;
}
int longest=0;
for (int i = 0; i < num.size(); i++)
{
if (hashlist[num[i]]==false)
{
continue;
}
int length=1;
int k1=num[i];int k2=k1;
while(hashlist[k1+1])
{
hashlist[k1+1]=false;
length++;
k1++;
}
while(hashlist[k2-1]&&k2-1>=0)
{
hashlist[k2-1]=false;
length++;
k2--;
}
longest=max(longest,length);
}
return longest;
}
};