简体   繁体   English

这个 python function 的时间复杂度是多少?

[英]Whats time complexity of this python function?

def hasPairWithSum(arr,target):
     for i in range(len(arr)):
         if ((target-arr[i])  in arr[i+1:]):
             return True

    return False    

In python, is time complexity for this function O(n) or O(n^2), in other words 'if ((target-arr[i]) in arr[i+1:])' is this another for loop or no?在 python 中,这个 function 的时间复杂度是 O(n) 或 O(n^2),换句话说,'if ((target-arr[i]) in arr[i+1:])' 是另一个 for 循环或者没有? Also what about following function, is it also O(n^2), if not why:另外跟随function,是否也是O(n ^ 2),如果不是为什么:

def hasPairWithSum2(arr,target):
   seen = set() 
   for num in arr:
      num2 = target - num
      if num2 in seen:
         return True
      seen.add(num)
   return False

Thanks!谢谢!

The first version has a O(n²) time complexity:第一个版本的时间复杂度为O(n²)

Indeed the arr[i+1:] already creates a new list with n-1-i elements, which is not a constant time operation.实际上arr[i+1:]已经创建了一个包含n-1-i 个元素的新列表,这不是一个恒定时间操作。 The in operator will scan that new list, and in worst case visit each value in that new list. in运算符将扫描该新列表,并且在最坏的情况下访问该新列表中的每个值。

If we count the number of elements copied into a new list (with arr[i+1 ), we can sum those counts for each iteration of the outer loop:如果我们计算复制到新列表中的元素数量(使用arr[i+1 ),我们可以对外部循环的每次迭代将这些计数相加:

  n-1
+ n-2
+ n-3
+ ...
+ 1
+ 0

This is a triangular number , and equals n(n-1)/2 , which is O(n²) .这是一个三角数,等于n(n-1)/2 ,即O(n²)

Second version第二版

The second version, using a set , runs in O(n) average time complexity.第二个版本使用set ,平均时间复杂度为O(n)

There is no list slicing here, and the in operator on a set has -- contrary to a list argument -- an average constant time complexity.这里没有列表切片,并且集合上的in运算符具有 - 与列表参数相反 -平均恒定时间复杂度。 So now every action within the loop has an (average) constant time complexity, giving the algorithm an average time complexity of O(n) .所以现在循环中的每个动作都有一个(平均)常数时间复杂度,给算法一个O(n)的平均时间复杂度。

According to the python docs , the in operator for a set can have an amortised worst time complexity of O(n) .根据python 文档,集合的in运算符的摊销最差时间复杂度为O(n) So you would still get a worst time complexity for your algorithm of O(n²) .因此,对于O(n²)的算法,您仍然会得到最差的时间复杂度。

It's O(n^2)这是 O(n^2)

First loop will run n times and second will run (nm) for every n.第一个循环将运行 n 次,第二个循环将运行 (nm) 每个 n。 So the whole thing will run n(nm) times that is n^2 - nm .所以整个事情将运行n(nm)次,即n^2 - nm Knowing that m<n we know that it has a complexity of O(n^2)知道m<n我们知道它的复杂度为 O(n^2)

But if it's critical to something you might consult someone who is better at that.但是,如果它对某件事很重要,您可能会咨询在这方面做得更好的人。

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

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