```
public int longestConsecutive(int[] num) {
Set<Integer> set = new HashSet<Integer>(num.length);
for (int n: num) {
set.add(n);
}
int maxLength = 0;
for (int n: num) {
if (set.contains(n)) {
int length = 1;
int next = n - 1;
while (set.contains(next)) {
length++;
set.remove(next);
next--;
}
next = n+1;
while (set.contains(next)) {
length++;
set.remove(next);
next++;
}
if (length > maxLength) {
maxLength = length;
}
}
}
return maxLength;
}
```

The basic idea is put all integers into a set. Iterate all the integers and for every integer try to find its consecutive numbers in the set and accumulate the length. The trick is remove the integer whenever it has been visited, which makes the process O(n) because every integer will only be visited once.