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

为何最长连续序列Python代码运行时长远超预期?

问题背景

给定一个未排序元素列表,需找出最长连续元素序列的长度,预期时间复杂度为O(N)。示例:输入[4,7,1,100,28,2,3],输出为4,对应最长连续序列[1,2,3,4]。

实现情况

我使用Python结合set和defaultdict实现了该问题的解决方案,代码如下:

from collections import defaultdict as maps
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        nums = set(nums); # 去重
        n = len(nums);
        if n == 0: return 0;
        if n == 1: return 1;
        present = maps(int);
        # 将元素存入defaultdict作为键,用于快速判断存在性
        for i in nums:
            present[i] = 1;
        i = 0; curr = 0; cnt, maxx = 0, 0; visset = {i for i in nums}
        while n > 0:
              # 用while循环是因为直接遍历set时修改集合会中断循环
            
            cnt = 1;
            for ind in visset:
                curr = ind; n -= 1; 
                visset.remove(ind); break; # set的remove操作理论上是O(1)
            # 查找当前元素左侧的连续序列
            curr, temp = curr, curr;
            while n > 0:
                if present[curr - 1]:
                    curr -= 1; n -= 1; 
                    visset.remove(curr); cnt += 1;
                else:
                    break;
            # 查找当前元素右侧的连续序列
            while n > 0:
                if present[temp + 1]:
                    temp += 1; n -= 1; 
                    visset.remove(temp); cnt += 1;
                else:
                    break;
            maxx = max(cnt, maxx);
        maxx = max(cnt, maxx);
        return maxx
性能疑问

这段代码运行时长约7000ms,远超预期;但将set替换为字典,用del dictt[i]替代set的remove()操作后,运行时长降至2000ms。请问为何原代码运行时长久高于预期?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:02:26