Well, below is a O(n) time and O(n) space solution. To outline the algorithm, first put all the elements into a map. The make a second pass over the input and for each element (that still exists in the map), erase the number and its neighboring numbers, and in the process count the length of consecutive sequence.

```
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_set<int> map;
for (unsigned i = 0; i < num.size(); ++i) {
map.insert(num[i]);
}
int longest = 0;
for (unsigned i = 0; i < num.size(); ++i) {
if (map.find(num[i]) == map.end()) continue;
map.erase(num[i]);
int subSeq = 1;
int n = num[i] - 1;
while ((map.find(n) != map.end())) {
++subSeq;
map.erase(n--);
}
n = num[i] + 1;
while (map.find(n) != map.end()) {
++subSeq;
map.erase(n++);
}
longest = (subSeq > longest) ? subSeq : longest;
}
return longest;
}
};
```