简体   繁体   English

Python 中“set”和“if item in array”的时间复杂度是多少?

[英]What is Time complexity of "set" and "if item in array" in Python?

I need to check if a number and its double exist in an array.我需要检查一个数字及其双精度数是否存在于数组中。 This code using set to solve it.这段代码使用set来解决它。 However I am not sure the Time complexity is better than O(N^2) .但是我不确定时间复杂度是否优于O(N^2) I use the for loop and if 2*item in s like below.我使用for loopif 2*item in s如下所示。 Isn't it to know whether the item is in an array, we use another O(N) .不是要知道该项目是否在数组中,我们使用另一个O(N) Which mean O(N^2) in total?这意味着总共O(N^2) If it is optimal, how can I implement the codes in C without using nested loop ?如果它是最佳的,我如何在不使用nested loop的情况下实现 C 中的代码?
Thanks a lot!非常感谢!

  def checkIfExist(arr]) -> bool:
    s = set(array)
    for item in s:
        if 2 * item in s and item != 0:
            return True
    if arr.count(0) >= 2:
        return True
    return False

The time complexity of the 'in' operator for sets in python is on average O(1) and only in the worst case O(N), since sets in python use a HashTable internally. python 中集合的“in”运算符的时间复杂度平均为 O(1),仅在最坏的情况下为 O(N),因为 python 中的集合在内部使用 HashTable。

So your function's time complexity on average should be O(N) and only in the worst case will be O(N^2), where N is the length of the array.所以你的函数的平均时间复杂度应该是 O(N),只有在最坏的情况下才会是 O(N^2),其中 N 是数组的长度。

More here https://wiki.python.org/moin/TimeComplexity更多在这里https://wiki.python.org/moin/TimeComplexity

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM