题目
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
解题思路
代码
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
s = set(nums)
res = 0
for n in nums:
if n - 1 in s:
continue
cur = n + 1
while cur in s:
cur += 1
res = max(res, cur - n)
return res