假设我们有以下代码。
def problem(n):
list = []
for i in range(n):
list.append(i)
length = len(list)
return list
如果不计算O(n)
,程序的时间复杂度为len(list)
。但是,如果这样做,时间复杂度是O(n * log(n))
还是O(n^2)
?
答案 0 :(得分:1)
否,len()函数在python中具有恒定的时间,并且不依赖于元素的长度,上述代码的时间复杂度将保持for i in range(n)
循环为O(N)。 Here is the time complexity用于许多CPython函数,例如len()! (在表格中获取长度)