简体   繁体   English

具有因变量和对数增量的嵌套循环的时间复杂度

[英]Time complexity of Nested loop with dependent variable and logarithmic increment

what is the time complexity of this loop, O(N) or O(N (logN ))这个循环的时间复杂度是多少, O(N)O(N (logN ))

also can you explain how you deduced你也可以解释一下你是如何推断的

for (int i = 1; i <= n;  i *= 2) {   
    for (int j = 0; j < i; j++) {
        // Statement(s) that take(s) constant time
   }
}

i have an explanation but it feels wrong我有一个解释,但感觉不对

education.io 上的解释

I think you are confused because of the statement O(n + log(n)) , as you thought that the outer loop runs logN times and inner loop runs N times so the answer should be O(NlogN) .我认为您因为语句O(n + log(n))感到困惑,因为您认为外循环运行logN次而内循环运行N次,所以答案应该是O(NlogN) You are wrong here because the inner loop doesn't run N times, it only runs i times as explained.你在这里错了,因为内循环没有运行N次,它只按照解释运行了i次。 Now when you sum all the i over outer loop, you will get that 2*2^k - 1 statement.现在,当您在外循环上对所有i求和时,您将得到2*2^k - 1语句。 This will come out to be order of N as given in the explanation.这将是解释中给出的N阶。

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

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