```
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int len = 0, candidate, val;
unordered_set<int> set(nums.begin(), nums.end());
while (!set.empty()) {
val = *set.begin();
set.erase(val);
candidate = 1;
for (int i = val + 1; set.find(i) != set.end(); ++i) {
set.erase(i);
candidate++;
}
for (int i = val - 1; set.find(i) != set.end(); --i) {
set.erase(i);
candidate++;
}
len = max(len, candidate);
}
return len;
}
};
```