【发布时间】:2020-05-21 05:02:06
【问题描述】:
我不明白为什么 res = res + res 的复杂度是 O(n)。在这段代码中, res 在每次迭代中都会加倍它的大小,因此该行的复杂性随着每次迭代而变化,如下所示:
2 + 4 + 8 + ... + n = O(n)
我很困惑为什么这个系列等于 O(n)。
def ones (n): # complexity O(n)
res = [1] # 1 = O (1)
while len ( res ) < n: # 1 + 1 ... + 1 ( log n times ) = O(log n)
res = res + res # 2 + 4 ... + n = O(n) Why this is O(n)
return res # 0 = O (0)
【问题讨论】:
-
res + res是 O(len(res)),并不比 O(n) 复杂,因为len(res) < n
标签: python time-complexity complexity-theory code-complexity