Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.size()==0) return 0;
std::sort(nums.begin(),nums.end());
int len = nums.size();
int pre = nums[0];
int current ;
int count = 1;
int max = count;
for(int i=1; i<nums.size(); i++)
{
if(nums[i]==(pre+1))
count++;
else if(nums[i]>=(pre+2))
{
max = std::max(max, count);
count = 1;
}
pre = nums[i];
}
max = std::max(max, count);
return max;
}
};