leetcode/0128_longest-consecutive-sequence/python3/solution.py
2022-04-05 05:28:58 +05:30

32 lines
761 B
Python

# Time: O(N)
# Space: O(N)
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
visited = {}
for _, num in enumerate(nums):
visited[num] = False
maxl = 0
for _, num in enumerate(nums):
if visited[num]:
continue
l = 1
prev = num - 1
while prev in visited:
visited[prev] = True
l += 1
prev -= 1
next = num + 1
while next in visited:
visited[next] = True
l += 1
next += 1
maxl = max(maxl, l)
return maxl