leetcode hot100 最长连续子序列 哈希表 medium

大 O 的加法规则 :O(f(n))+O(g(n))=O(max(f(n),g(n)))

例如:

python 复制代码
nums_sorted  = sorted(nums)
for i in range(1, len(nums_sorted)):
    ... ...

时间总复杂度 = 排序 + 遍历 。O(nlog⁡n) + O(n) = O(max(n log n, n)) = O(n log n )

(增长速度:n log n > n

时间复杂度 :O(n log n )

python 复制代码
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if not nums:
            return 0

        nums_sorted  = sorted(nums)
        print(nums_sorted)

        max_len = 1
        cur_len = 1

        for i in range(1, len(nums_sorted)):
            if nums_sorted[i] == nums_sorted[i-1] + 1:   # # 连续
                cur_len +=1    # 如果最后一个数字在最长连续里,此时 max_len没有更新,就会退出循环了
            elif nums_sorted[i] == nums_sorted[i-1] :   # # 重复,题意要求,重复不算断开
                cur_len = cur_len
            else:
               max_len = max(cur_len, max_len)
               cur_len = 1

        return max(max_len, cur_len)
        

时间复杂度 :O(n)

要真正实现 O(n) → 需要用 哈希表法:

遍历每个数字,只从"序列起点"开始向右查找连续数字,这样每个数字最多访问一次 → O(n)

子序列起点:n是最小数字

python 复制代码
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:

        if not nums:
            return 0
        num_set = set(nums)   # 去重,题意重复的不算
        maxlen = 1

        for n in num_set:
            if n-1 not in num_set:   # 子序列起点:n是最小数字
                temp = n
                cur_len =1  # 子序列长度

                while temp+1 in num_set:   # 走完起点为n的子序列  # O(1) 查找
                    temp = temp+1 
                    cur_len += 1

                # 跳出while,走完子序列
                maxlen = max(maxlen, cur_len)

        return maxlen
相关推荐
小羊在睡觉7 小时前
力扣239. 滑动窗口最大值
数据结构·后端·算法·leetcode·go
大大杰哥8 小时前
leetcode hot100(4)矩阵
算法·leetcode·矩阵
叶小鸡9 小时前
小鸡玩算法-力扣HOT100-动态规划(上)
算法·leetcode·动态规划
凌波粒9 小时前
LeetCode--513.找树左下角的值(二叉树)
java·算法·leetcode
一只小逸白11 小时前
LeetCode Go 常用函数速查表
linux·leetcode·golang
Tisfy12 小时前
LeetCode 3043.最长公共前缀的长度:哈希表(不转string)
算法·leetcode·散列表·题解·哈希表
承渊政道12 小时前
【贪心算法】(经典实战应用解析(六):整数替换、俄罗斯套娃信封问题、可被三整除的最⼤和、距离相等的条形码、重构字符串)
c++·算法·leetcode·贪心算法·排序算法·动态规划·哈希算法
人道领域12 小时前
【LeetCode刷题日记】654.最大二叉树:递归算法详解
java·算法·leetcode
失去的青春---夕阳下的奔跑1 天前
560. 和为 K 的子数组
数据结构·算法·leetcode
m0_629494731 天前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表