关于力扣:Leetcode-128-Longest-Consecutive-Sequence-最长连续序列-On

5次阅读

共计 514 个字符,预计需要花费 2 分钟才能阅读完成。

原题链接

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
正文完
 0