【问题标题】:What will be the time complexity of the following program以下程序的时间复杂度是多少
【发布时间】:2020-02-13 17:13:26
【问题描述】:

谁能找到以下python 3.6程序的时间复杂度:

试图找到,我的答案O(N*n),其中 N 是第一个循环的范围,n第二个 for 循环的范围,它在第一个 for 循环内

这个程序是针对codechef上的https://www.codechef.com/FEB20B/problems/SNUG_FIT问题。

N=int(input())
for _ in range(N):
    S=0
    n=int(input())
    A=list(map(int, input().split()))[:n] #Assume amount of inputs to be strictly of n numbers
    B=list(map(int, input().split()))[:n]
    A.sort();A.reverse()
    B.sort();B.reverse()

    for i in range(0,len(A)): # Here range is n (same as len(A))
        if A[i]>=B[i]:
            S=S+B[i]
        else:
            S=S+A[i]
    print(S)

【问题讨论】:

  • 你也忘记了 O(n) 的排序,我相信它运行 O(n log n)。
  • 不可能在不知道input().split() 多长时间的情况下说出来(您在n 处明确将它们切断,所以大概它们比这更长)。
  • @HeapOverflow 我想我们也不知道input() 会阻塞多久。
  • 不确定分析整个事情的复杂性是否有意义 - 外循环仅针对 T 测试用例重复。您通常有兴趣分析的是输入后的内部算法。你计算S的循环是O(n)和sort is O(n log n),所以算法的复杂度是O(n log n)。无论如何,这个算法是否解决了挑战?
  • list.sort() 使用en.wikipedia.org/wiki/Timsort

标签: python algorithm data-structures time-complexity complexity-theory


【解决方案1】:

for 循环是O(N),在里面你对O(nlog(n)) 进行排序,所以总体上它变成O(Nnlog(n))

之后你有另一个运行O(n)的for循环。

现在整体时间复杂度如下所示:

O(N( nlogn + n)) 实际上是O(Nnlog(n))

【讨论】:

  • 我已经理解你的回答了。但是,具有 if else 条件的 for 循环的运行时间是多少?
  • @Abhishek If else 条件对时间复杂度没有任何影响
【解决方案2】:

@Pritam Banerjee 写道 -

O(N( nlogn + n)) 实际上是O(Nlog(n))

其实不是这样的

我把它和代码一起描述得更清楚了。

N=int(input())
for _ in range(N):    # O(N)
    S=0
    n=int(input())
    # The following line is O(n)
    A=list(map(int, input().split()))[:n] #Assume amount of inputs to be strictly of n numbers
    # This line is also O(n)
    B=list(map(int, input().split()))[:n]
    A.sort();A.reverse()    # this is O(nlog(n))
    B.sort();B.reverse()    # this is also O(nlog(n))

    for i in range(0,len(A)): # Here range is n (same as len(A))  # this is O(n)
        if A[i]>=B[i]:
            S=S+B[i]
        else:
            S=S+A[i]
    print(S)

所以总的来说O(N( n + n + nlog(n) + nlog(n) + n)

我们可以通过以下方式计算——

  O(N( n + n + nlog(n) + nlog(n) + n)
= O(N( 3n + 2nlog(n))
= O(N (n + nlog(n)) (we can eliminate const number when determining complexity)
= O(N(nlog(n)) (as n > nlog(n), so we can eliminate the small part)
= O(N*nlog(n))

所以总体复杂度是O(N*nlog(n)不是 O(Nlog(n)

O(N*nlog(n)O(Nlog(n) 之间的区别更大。

希望这个post对你有很大帮助。

谢谢。

【讨论】:

  • 这显然只是 Pritam Banerjee 回答中的一个错字;他在第一句话中写了O(Nnlog(n))
  • 是的,明白了。所以这是他的问题。在我发表评论后,他明白了这一点。那我为什么要消极呢?搞笑!
  • 您的答案可能被否决了,因为写一个长篇大论为什么拼写错误是没有用的。您可以在 Pritam 的回答中写一个简短的评论,指出错字或提出修改它的建议。 “这是他的问题”没有抓住重点。
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 2021-02-28
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多