【发布时间】: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