【问题标题】:Compexity of a list that double its size列表的复杂性使其大小翻倍
【发布时间】: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) &lt; n

标签: python time-complexity complexity-theory code-complexity


【解决方案1】:

永远不会大于N 的列表大小加倍的复杂度是O(N),但是,由于您在重复logN 次的循环中执行此操作,因此您的函数的整体复杂度将是@ 987654324@.

我宁愿推荐线性解决方案,例如:

def ones(n) :
    return [1] * n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 2015-08-29
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    相关资源
    最近更新 更多