代码如下所示。
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
set_nums = set(nums)
maxlength = 0
for x in set_nums:
if x - 1 not in set_nums:
tmplength = 1
current_num = x
while current_num + 1 in set_nums:
current_num += 1
tmplength += 1
maxlength = max(maxlength, tmplength)
return maxlength
代码有两个核心要点:
1. 由于题目要求时间复杂度为O(n),使用set()函数过滤掉列表中的重复元素,因为当出现重复元素时(如nums=[1, 1, 1, 1,... ]时),while循环会导致复杂度增加;
2. if x - 1 not in set_nums:是这段代码的灵魂,这判断了x-1是否在数组中,因为假设x-1在数组中,以x-1开头的连续序列一定超过以x开头的(这种情况下x-1, x均存在)。因此当x-1存在时可以直接跳过,只需判断x-1不存在时的情形