原题链接

https://leetcode-cn.com/probl...

解题思路

思路外围:nums中只有一部分数字有可能成为最长序列的起始点,咱们只遍历以它们为终点的间断序列

步骤:

  1. set(nums)去重:遍历set(sum),找出“合乎终点资质的下标:i”:
    i-1不在set(nums)中
    i+1在set(nums)中
  2. 遍历这些点,计算以它们为终点的最长间断序列长度
  3. 工夫复杂度O(n)证实:
    因为上述第3步中:遍历的序列之间没有重合局部,所以总遍历次数小于等于len(nums)

欢送在我的博客轻松摸索更多思路

代码

class Solution:    def longestConsecutive(self, nums: List[int]) -> int:        if not nums:            return 0        n=set(nums)        starting_points=set()        for i in n:            if (not i-1 in n) and (i+1 in n):                starting_points.add(i)                max_l=1        for i in starting_points:            cur_l=1            while(i+1 in n):                cur_l+=1                i+=1            max_l=max(max_l,cur_l)        return max_l