2022-04-04 23:58:58 +00:00
|
|
|
# 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
|
|
|
|
|