Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Example
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Clarification
Your algorithm should run in O(n) complexity.
Tags Expand
class Solution {
public:
/**
* @param nums: A list of integers
* @return an integer
*/
int longestConsecutive(vector<int> &num) {
// write you code here
map<int, int> hashTable;
for (int i=0; i<num.size(); i++)
{
if (hashTable.count(num[i]) == 0)
hashTable[num[i]] = 1;
}
int maxLen = 0;
for (int i=0; i<num.size(); i++)
{
if (hashTable.count(num[i]) != 0)
{
int curLen = 1;
hashTable.erase(num[i]);
int before = num[i]-1;
while (hashTable.count(before) != 0)
{
curLen++;
hashTable.erase(before);
before--;
}
int after = num[i]+1;
while (hashTable.count(after) != 0)
{
curLen++;
hashTable.erase(after);
after++;
}
maxLen = max(maxLen, curLen);
}
}
return maxLen;
}
};