gpt4 book ai didi

python - 函数的时间复杂度

转载 作者:太空狗 更新时间:2023-10-30 00:20:03 24 4
gpt4 key购买 nike

我正在尝试找出函数的时间复杂度 (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 循环中发生了什么。

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

最佳答案

对于这样一个简单的案例,您可以 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 ):它假设 r += 1 是 O (1) 如果 rO(log n) 位 ( model has words with log n bits )。

第二个循环更简单:i//= 2i >>= 1nΘ(log n) 数字,每次迭代都会丢弃一个二进制数字(右移),因此整个循环是 Θ(log n) 如果我们假设 log(n) 位的 i >> 1 移位是 O(1) 操作(与在第一个示例中)。

关于python - 函数的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28572516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com