如果堆栈操作是恒定时间o(1),则该算法的时间复杂性是多少?
二进制转换: 我们正在输入一个正整数n,输出是堆栈上N的二进制表示。
这里的复杂时间会是多少?我认为这是o(n),因为while循环每次都会减少,这意味着一组输入大小的迭代'n'降低到n/2,n/4,n/8等。
应用几何序列的总和n = a,r = 1/2,我们得到2n。
任何帮助!我仍然是菜鸟。
create empty stack S
while n > 0 do
push (n mod 2) onto S
n = floor(n / 2)
end while
return S
BinaryConversion:
We are inputting a positive integer n with the output being a binary representation of n on a stack.
What would the time complexity here be? I'm thinking it's O(n) as the while loop halves every time, meaning the iterations for a set of inputs size 'n' decrease to n/2, n/4, n/8 etc.
Applying sum of geometric series whereby n = a and r = 1/2, we get 2n.
Any help appreciated ! I'm still a noob.
create empty stack S
while n > 0 do
push (n mod 2) onto S
n = floor(n / 2)
end while
return S
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果循环是循环
,那么复杂性将为
o(n + n/2 + n/4 ... 1)
〜o(n)
,您的答案将是正确的。但是,复杂性应该是外循环运行的次数,因为每次迭代中完成的工作量为
o(1)
。因此,答案将为o(log(n))
(因为n
每次都会减半)。If the loop was
Then the complexity would have been
O(n + n/2 + n/4 ... 1)
~O(n)
, and your answer would have been correct.Here however, the complexity will should be the number of times the outer loop runs, since the amount of work done in each iteration is
O(1)
. So the answer will beO(log(n))
(sincen
is getting halved each time).迭代的数量是您必须将n除以2的次数获得0,即o(log n)。
The number of iterations is the number of times you have to divide n by 2 to get 0, which is O(log n).