javascript - 对数复杂度 : Either the book has a typo or what's happening here?

标签 javascript algorithm data-structures big-o

我现在正在研究算法,我遇到过一个例子,我的回答是 Infinite loop但在正确答案中,它说它是 O(log2n) .

function someFunc(n) {

    for(var i = 0; i < n; i * 2) { // I think that Infinite loop cannot be O(log2n), can it?
        console.log(i);
    }

}
我在这里有点困惑。我不明白为什么,因为它和 Infinite loop 一样下面,不是吗?
function loop(n) {

    while(true) {
        console.log(n)
    }

}
资料来源:Sammie Bae - JavaScript 数据结构和算法 - 2019(第 1 章)

最佳答案

这是书中明显的错误。我找到了 a PDF of chapter 1 on the publisher's website正如你所说的(第 10 页):

EXERCISE 5

1   function someFunction(n) {

2

3       for (var i=0;i<n;i*2) {

4           console.log(n);

5       }

6

7   }

(下一页)

Answers
[...]
5. O(log2n) Logarithmic complexity. For a given n, this will operate only log2n times because i is incremented by multiplying by 2 rather than adding 1 as in the other examples.


正如评论中所指出的,这个循环实际上永远不会退出。
作者(可能)维护了一个可以找到源代码的 github 存储库,因此您可以对 the relevant file 提出修复建议。

关于javascript - 对数复杂度 : Either the book has a typo or what's happening here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69914393/

相关文章:

php - Magento 内置日历无法在管理后端工作

java - 从数组创建二叉树

c++ - spoj 上的抗印迹系统

r - 用给定的长度和内容初始化列表

javascript - 如何在函数中处理时获取更新的值

javascript - JS脚本中的执行顺序

algorithm - 我可以对这个递推关系使用大师定理吗?

java - 线性 "smoothed"函数使用查找表

c# - 与类实例具有相同类型的成员

javascript - 为什么 ngMessages 警报只出现一次?