33 lines
932 B
Python
33 lines
932 B
Python
def longestConsecutive(nums):
|
|
"""
|
|
:type nums: List[int]
|
|
:rtype: int
|
|
"""
|
|
# If list empty, return 0
|
|
if not nums:
|
|
return 0
|
|
|
|
# Create a set for O(n) search
|
|
num_set = set(nums)
|
|
longest_streak = 0
|
|
|
|
for num in num_set:
|
|
if num - 1 not in num_set: # Start of a potential streak
|
|
current_num = num
|
|
current_streak = 1
|
|
|
|
while current_num + 1 in num_set: # Continue the streak
|
|
current_num += 1
|
|
current_streak += 1
|
|
|
|
longest_streak = max(longest_streak, current_streak)
|
|
|
|
return longest_streak
|
|
|
|
|
|
|
|
# print(longestConsecutive([100,4,200,1,3,2]))
|
|
# print(longestConsecutive([0,3,7,2,5,8,4,6,0,1]))
|
|
# print(longestConsecutive([1,3,5,2,4]))
|
|
# print(longestConsecutive([9,1,4,7,3,-1,0,5,8,-1,6]))
|
|
print(longestConsecutive([1,2,0,1])) |