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> &num)
{
if (num.empty()) return 0;
set<int> nums(num.begin(), num.begin() + num.size());
int maxN = 1;
int cur = INT_MIN;
int count = 1;
for (set<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)
{
if (*iter == cur + 1)
{
count++;
cur = *iter;
}
else
{
maxN = maxN > count ? maxN : count;
count = 1;
}
cur = *iter;
}
maxN = maxN > count ? maxN : count;
return maxN;
}
};