【问题标题】:Time complexity of a function函数的时间复杂度
【发布时间】:2015-02-17 22:37:57
【问题描述】:

我正在尝试找出函数的时间复杂度 (Big-O) 并尝试提供适当的原因。

第一个函数:

r = 0
# Assignment is constant time. Executed once. O(1)
for i in range(n):
    for j in range(i+1,n):
        for k in range(i,j):
            r += 1
            # Assignment and access are O(1). Executed n^3

像这样。

我看到这是三重嵌套循环,所以它必须是 O(n^3)。 但我认为我在这里的推理非常薄弱。我真的不明白发生了什么 在这里的三重嵌套循环内

第二个功能是:

i = n
# Assignment is constant time. Executed once. O(1)
while i>0:
    k = 2 + 2
    i = i // 2
    # i is reduced by the equation above per iteration.
    # so the assignment and access which are O(1) is executed
    # log n times ??

我发现这个算法是 O(1)。但就像第一个函数一样, 我看不到while循环中发生了什么。

有人能详细解释一下两者的时间复杂度吗 职能?谢谢!

【问题讨论】:

  • 嵌套循环几乎总是二次的,除非你在做一些持续的工作,你的第二个例子是log(n)
  • 谢谢。对于第二个示例,我们是否忽略了 i = n 部分?
  • i = n 只是一个赋值,之后我们将 n 每次迭代减半,就像使用二分搜索一样
  • 第一个循环是 O(n^3),而不是 O(n^2)。
  • 此参考可能会有所帮助:wiki.python.org/moin/TimeComplexity

标签: python time-complexity


【解决方案1】:

对于这样一个简单的案例,你可以find the number of iterations of the innermost loop as a function of n exactly:

sum_(i=0)^(n-1)(sum_(j=i+1)^(n-1)(sum_(k=i)^(j-1) 1)) = 1/6 n (n^2-1)

Θ(n**3)时间复杂度(see Big Theta):如果rO(log n)数字(model has words with log n bits),则假设r += 1是O(1)。

第二个循环更简单:i //= 2i >>= 1nΘ(log n) 数字,每次迭代都会丢弃一个二进制数字(右移),因此如果我们假设 i >> 1log(n) 移位,整个循环的时间复杂度是 Θ(log n) digits 是 O(1) 运算(与第一个示例中的模型相同)。

【讨论】:

  • 我试图做 WolframAlpha 的事情,但失败了,你能展示一下步骤吗?
  • 没有步骤,点击链接应该可以看到结果了。
  • @Jasper:我忘记了如何手工操作(计算机做得太好了——如果不是用于购物清单的话;我忘记了如何写)。寻找类似How to find the partial sum of a given series? 的东西来获得准确的结果(优点是TeX 公式在那里呈现)。或者如果你想从头开始学习how to find partial sums
  • @Jasper:这里是my attempt to do it manually step by step。答案不一样;)你可以重复这个过程并找出我犯错的地方。
【解决方案2】:

首先,对于第一个函数,时间复杂度似乎更接近O(N log N),因为每个循环的参数每次都在减小。

另外,对于第二个函数,运行时间为 O(log2 N)。除了,说 i == n == 2。在一次运行之后,我是 1。在另一次运行之后,我是 0.5。另一个 i 是 0.25。依此类推……我想你会想要 int(i)。

对于每个函数的严格数学方法,您可以访问https://www.coursera.org/course/algo。对于这类事情来说,这是一门很棒的课程。我的计算有点草率。

【讨论】:

  • // 在 Python 中进行整数除法
  • 第二个函数 O(log N) 怎么样?它不应该是 O(1),因为常数优于对数吗?
  • “常数优于对数”?没有。
猜你喜欢
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 2022-01-15
  • 2018-05-29
  • 2015-08-01
相关资源
最近更新 更多