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
.
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.empty()) return 0;
sort(nums.begin(), nums.end());
int left, right, ans = 1, tmp;
for(int i = 0; i < nums.size() - 1; i++){
left = nums[i];
while(nums[i + 1] - nums[i] <= 1 && i < nums.size() - 1)
i++;
right = nums[i];
tmp = right - left + 1;
ans = max(ans, tmp);
}
return ans;
}
};