Using two sets, one for the original list of numbers and the other for recording those visited numbers. For each n in num check if its neighboring numbers are in the list, and add those in the list to the visited set

```
class Solution:
# @param num, a list of integer
# @return an integer
def longestConsecutive(self, num):
numlen, longest = len(num), 0
numset, visited = set(num), set()
for n in numset:
if n in visited: continue
visited.add(n)
m, length = n + 1, 1
while m in numset:
visited.add(m)
length, m = length + 1, m + 1
m = n - 1
while m in numset:
visited.add(m)
length, m = length + 1, m - 1
longest = max(length, longest)
return longest
```