【问题标题】:Run-time complexity of nested for-loops嵌套 for 循环的运行时复杂度
【发布时间】:2019-03-17 03:45:35
【问题描述】:
for(a = c; a > 0; a/=2) 
    for(b=0; b < 2*a; b++)

我已经得出结论,这是 O(nlogn) 运行时,但我不确定.. 我的逻辑是最外层的for循环运行logn次,每次除以2,然后最里面的for循环运行减半数的2倍;因此它运行 n 次。

【问题讨论】:

标签: algorithm time-complexity big-o complexity-theory nested-loops


【解决方案1】:
#include <iostream>

int main() {

    int c = 16;

    for(int a = c; a > 0; a/=2) {

        for(int b =0; b < 2*a; b++)
            std::cout << "*";

        std::cout << std::endl;
    }
}

输出

********************************
****************
********
****
**
  • 在您看到的第一个内部循环中,b 从 0 到 2*a
  • 在你看到的第二个内循环中,b 从 0 到 2*(a/2)
  • 在您看到的第三个内循环中,b 从 0 到 2*(a/4)

将这些相加:2a + a + a/2 + ...+1 = 2a -1 \in O(n),因为输入大小。

【讨论】:

  • 啊,我明白了,这是有道理的。谢谢。我只是想问一下,因为我似乎对时间复杂度这个话题很迷茫。我应该如何处理这些问题?它也是 Big Theta(n) 吗?
  • 搜索和阅读。通常,您的书籍和教授必须在讲座中定义。 stackoverflow.com/questions/10376740/…
  • 顺便说一句,如果内循环运行时间为 O(n),我们是否也必须检查外循环运行的时间?这似乎是 O(logn) 时间,所以嵌套在一起的两个 for 循环的运行时复杂度将是 O(nlogn) 对吗?也应该是 Big Theta(nlogn) 对吧?
  • 如果您说内部循环完全运行,答案是肯定的。第一行已经包含金额计算。因此 > log n。 a+a/2+a/4+...+/1 = a-1。因此结果 2a-1 \in O(n).
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2022-01-21
  • 1970-01-01
相关资源
最近更新 更多