128. Longest Consecutive Sequence
Содержание
- Save all numbers in set to make it possible to get number at
O(1)
. - For each element look for the
current+1
element if exists.
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
res = 0
nset = set(nums)
for x in nset:
if x - 1 not in nset: # prevent double calculations
_max = 1
cur = x
while cur + 1 in nset:
_max += 1
cur += 1
res = max(_max, res)
return res