python - python中输入过大如何处理?

标签 python performance runtime-error time-complexity large-files

我是一个初学者,我正在练习一个关于 hackerrank 的问题。 我编写此代码是为了解决因大输入而超时的问题:

    K = int(input())
    roomnos = input().split()
    setroomnos = set(roomnos)
    for r in setroomnos:
        if roomnos.count(r) == 1:
            print(r)
            break

下一个测试用例被法官接受

    K = int(input())
    roomnos = [int(i) for i in input().split()]
    setroomnos = set(roomnos)
    c = (K * sum(setroomnos) - sum(roomnos)) // (K - 1)
    print(c)

您能否解释一下为什么第一个输入因大输入而超时而第二个输入正常 PS: 基本操作是找到一个在列表中只出现一次的 no,而不是其他出现 K 次的 no

最佳答案

您的第一个解决方案使用 O(n) for ,其中包含 O(n) count - 导致 O(n^2) 复杂性。您的第二个示例不会以这种方式嵌套操作,因此复杂度为 O(n)。

关于python - python中输入过大如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36549640/

相关文章:

VBA (Visual Basic) : ComboBox (Form Control) - Object doesn't support this property or method

Excel 2013 VBA 运行时错误 13 类型不匹配

ios-simulator - 使用 iOS 模拟器的 AVAudioPlayer 错误

Python——在进程之间共享一个 Numpy 数组?

python - 二维数组每列的第一个和最后一个数字 1 的索引

python - 将 block 矩阵的每个 block 与 NumPy 中的不同系数相乘

performance - 在没有共享文件夹的Windows上,Boot2docker非常慢

c# - PerformanceCounter 创建需要很长时间

python - 谁能解释为什么 `skimage.measure.perimeter(img)` 返回这个结果?

python - Kivy - 在 ModalView 中按下按钮后更改屏幕