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

Python DSA:数组重复元素查找代码报错求助

数组重复元素查找代码报错排查请求

我编写了一段Python代码用于查找数组中的重复元素,自认为逻辑正确,但编译时出现错误,恳请帮忙排查。题目要求:给定大小为N、元素范围0到N-1的数组a[],找出所有出现多次的元素。

我的代码如下:

def duplicates(self, arr, n): 
        
        result = []
        a = []
        arr.sort()
        
        for i in arr:
            if i not in a:
                a.append(i)
                
            else:
                if i not in result:
                    result.append(i)
        
        if len(a) == n:
            result.append(-1)
        
        return result

报错原因分析及修正建议

  • 编译报错核心原因:函数定义里带了self参数,但如果这是一个普通独立函数而非类中的方法,调用时会因为缺少实例参数而报错。self是Python类实例方法的专用参数,只有在类内部定义方法时才需要,普通函数不需要这个参数。
  • 其他逻辑优化点:
    1. 用列表a判断元素是否已遍历的时间复杂度为O(n),整体效率较低,可改用集合seen来降低判断时间到O(1)。
    2. 原代码中len(a) == n用来判断无重复元素的逻辑,可直接改为判断result是否为空,更直观。

修正后的普通函数版本

def duplicates(arr, n): 
    result = []
    seen = set()
    arr.sort()
    
    for i in arr:
        if i not in seen:
            seen.add(i)
        else:
            if i not in result:
                result.append(i)
    
    if not result:
        result.append(-1)
    
    return result

符合题目元素范围特性的高效版本

利用题目中元素范围为0到N-1的特点,用数组标记法实现O(n)时间复杂度:

def duplicates(arr, n):
    result = []
    visited = [False] * n
    for num in arr:
        if visited[num]:
            if num not in result:
                result.append(num)
        else:
            visited[num] = True
    return result if result else [-1]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:05:30