题目链接:https://leetcode.cn/problems/WhsWhI/description/
在去重数据的集合内,如果当前元素在下一个连续元素在集合内,长度加1;
考虑到效率,此处我们只从连续序列中的更小的元素 开始统计;
即如果当前元素又比它更小的连续元素在集合能,则选择更小的开始;
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
res = 0
num_set = set(nums) # 去重
for num in num_set:
if num - 1 not in num_set:
cur_num = num
tmp_res = 1
while cur_num + 1 in num_set:
cur_num += 1
tmp_res += 1
res = max(tmp_res, res)
return res