题目链接:https://leetcode.cn/problems/longest-consecutive-sequence/
难度:中等
描述:
给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n)
的算法解决此问题。
提示:nums.length:[0, 100000]
题解
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
ret = 0
s = set(nums)
for num in nums:
if num - 1 not in s:
cur = num
temp_length = 1
while cur + 1 in s:
temp_length += 1
cur += 1
ret = max(ret, temp_length)
return ret