• [python 刷题] 128 Longest Consecutive Sequence


    [python 刷题] 128 Longest Consecutive Sequence

    题目:

    Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

    You must write an algorithm that runs in O(n) time.

    这题给了一个没有排序的数组,并且要求找出最长的连续序列

    最简单的方式其实还是排序,不过题目中要求时间复杂度 O ( n ) O(n) O(n),而排序的时间复杂度为 O ( n l o g ( n ) ) O(n log(n)) O(nlog(n))

    Union Find 也可以用来解这题,它的时间复杂度是 amortized linear,不过这个问题的话有一个 linear 的解。

    [100,4,200,1,3,2] 为例,假设有一个无限延长的 x 轴,所有的点在 x 轴上看起来是这个样子的:

    在这里插入图片描述

    这个情况下就比较清楚的可以看到哪个点在哪个 cluster 里,在实际的实现中,可以用一个 set 去存储所有出现的值,每次将值存入 cluster 中,都可以检查一下当前值是否是 cluster 的最小值,如果是的话,查看当前 cluster 的长度

    代码如下:

    class Solution:
        def longestConsecutive(self, nums: List[int]) -> int:
            num_set = set(nums)
            max_len = 0
            for num in num_set:
                if (num - 1) in num_set:
                    continue
    
                local_max = 1
                right = num + 1
                while right in num_set:
                    local_max += 1
                    right += 1
    
                max_len = max(max_len, local_max)
    
            return max_len
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    整体时间复杂度的分析:

    创建 set 的时间复杂度为 O ( n ) O(n) O(n)

    第一个 for 循环的时间复杂度为 O ( n ) O(n) O(n)

    查询当前值是否存在与 set 的时间复杂度为 O ( 1 ) O(1) O(1)

    第二个循环 while 在最差的情况下会跑 O ( n ) O(n) O(n) 次,但是因为有 if,的检查,所以这个情况最坏只会跑一次,而 O ( n + n ) O(n + n) O(n+n) 在大 O 里面依旧是 O ( n ) O(n) O(n),所以整体的时间复杂度为 O ( n ) O(n) O(n)

  • 相关阅读:
    JS中的继承以及不同的方式
    大数据学习(22)-spark
    SpringCloud Gateway网关梳理
    24.第12届蓝桥杯省赛真题题解
    微信小程序|基于小程序+C#实现聊天功能
    NSSCTF做题(6)
    C#版本与.NET版本对应关系以及各版本的特性
    量化交易笔记
    Oracle——常用的几种函数(含案例)
    C# string stringbuilder区别
  • 原文地址:https://blog.csdn.net/weixin_42938619/article/details/133111658