简体   繁体   English

带有条件内循环的 for 循环的 Big-O 表示法

[英]Big-O Notation of a for-loop with an conditional inner loop

I am trying to understand the time complexity of this program, and why.我试图了解这个程序的时间复杂度,以及为什么。 I've made some notes of what I think it is, but I'm unsure if I understood it correct.我已经对我的想法做了一些笔记,但我不确定我是否理解正确。

 public static int countSteps(int n) {
    int pow = 2;                             // O(1)
    int steps = 0;                           // O(1)
    for (int i = 0; i < n; i++) {            // O(n)
        if (i == pow) {                      // O(1)
            pow *= 2;                        // O(1)
            for (int j = 0; j < n; j++) {    // O(n)
                steps++;                     // O(1)
            }
        }
        else {
            steps++;                         // O(1)
        }
    }
    return steps; // O(1)
}

The inner loop spends a lot of time iterating through n every time the if-statement is triggered, does that affect the time complexity or is it still constant?每次触发 if 语句时,内部循环都会花费大量时间迭代 n,这会影响时间复杂度还是它仍然是常数?

The outer loop means it's at least O(n).外循环意味着它至少是 O(n)。 The inner loop will run only when i is a power of two, so it's O(n*log n).只有当i是 2 的幂时,内部循环才会运行,所以它是 O(n*log n)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM