You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode最长连续序列问题:count变量为何行为异常?

LeetCode题目:最长连续序列

问题描述:给定未排序的整数数组nums,返回最长连续元素序列的长度,算法需满足O(n)时间复杂度。
示例1:输入nums = [100,4,200,1,3,2],输出4,解释:最长连续序列为[1,2,3,4],长度为4。
示例2:输入nums = [0,3,7,2,5,8,4,6,0,1],输出9。

代码问题

以下Python代码运行时count变量行为异常:

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:

nums = [0,3,7,2,5,8,4,6,0,1]
nums = list(set(nums)) # O(n) operation 
res = 0
count = 1

if len(nums)==1: # edge case
    res = 1


for i in range(len(nums)-1):
    if abs(nums[i] - nums[i+1]) == 1:
        count+=1 
        print(count)
    else:
        res = max(res, count) 
        count = 1
    
print(res)

运行示例2时,最终输出的res为0(易被误以为是count输出了0);运行示例1时输出2、3、3,count变量表现不符合预期,问题原因及修正方案如下:

核心问题分析

  1. 数组未排序,遍历逻辑完全失效
    去重后的数组元素顺序无规律(Python 3.7+保留原数组插入顺序,但原数组本身乱序),相邻元素并非连续序列中的相邻数,导致abs(nums[i] - nums[i+1]) == 1的判断完全无法正确统计连续序列长度,count的累加毫无意义。

  2. 循环结束后未更新结果
    如果整个数组是完整的连续序列(比如示例2排序后),循环过程中不会触发else分支,res始终保持初始值0,最终输出的0易被误认为是count的输出;若最后一段元素是连续序列,也会漏掉对res的更新。

  3. 边界场景处理遗漏
    当数组长度大于1且最后一段为连续序列时,无法捕获这段序列的长度。

修正方案(满足O(n)时间复杂度)

不能使用排序(排序时间复杂度为O(nlogn)),正确做法是利用哈希集合快速查找:

class Solution:
    def longestConsecutive(self, nums: list[int]) -> int:
        num_set = set(nums)
        max_length = 0
        for num in num_set:
            # 仅从连续序列的起点开始统计(当前元素的前一个数不在集合中)
            if num - 1 not in num_set:
                current_num = num
                current_length = 1
                # 向后查找连续元素
                while current_num + 1 in num_set:
                    current_num += 1
                    current_length += 1
                max_length = max(max_length, current_length)
        return max_length

# 测试示例
nums1 = [100,4,200,1,3,2]
nums2 = [0,3,7,2,5,8,4,6,0,1]
sol = Solution()
print(sol.longestConsecutive(nums1)) # 输出4
print(sol.longestConsecutive(nums2)) # 输出9

内容的提问来源于stack exchange,提问作者mkj4332

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 11:50:24