简体   繁体   English

如何找到此代码块的时间复杂度(Big O)?

[英]How do I find the time complexity (Big O) of this block of code?

I am trying to understand how this O notation works and I have below here a block of code, and next to each LINE I will have a comment with the time complexity that I believe it to be. 我正在尝试了解这种O表示法是如何工作的,下面有一段代码,在每条LINE旁边,我都会有一个注释,说明时间复杂度。 If I am wrong please correct me and explain why my logic is not correct. 如果我错了,请纠正我,并解释为什么我的逻辑不正确。

Code #1 代码#1

for (int i = 0; i < n; i++) <<<<<<<<<<<<<<<<<<< O(1)*O(N)
 {
    for (int j = 0; j < 3; j++) <<<<<<<<<<<<<<< O(1)*O(1)
      {
        for (int k = 0; k < 3; k++) <<<<<<<<<<<<<<O(1)*O(1)
          {
            printf("%d", arr[i]); <<<<<<<<<<<<<<O(1)
           }
        printf("\n"); <<<<<<<<<<<<<<<<<<O(1)
    }

}

Running time = O(N), after adding everything up. 将所有内容相加后,运行时间= O(N)。

Code #2 代码#2

for (int i = 2; i <= n; i++) <<<<<<<<<<<<O(1)*O(N)
{
        int j;<<<<<<<<<<<<<<<<<<<<<<<O(1)
        printf("\n%d:", i);<<<<<<<<<<<<<<O(1)
        for(j = 2; j <= i; j = j * 2) <<<<<<<<<<<O(n-2)??????????
        {
            printf("%d ", j);<<<<<<<<<<<<<<O(1)
        }
         printf("\n%d:", i);<<<<<<<<<<<<<<<<<<<<O(1)
         for(int k = j/2; k >= 2; k = k / 2)<<<<<<<<<<<<<I am not sure of this one
        {
             printf("%d ", k);
        }
  }

Running time: Unsure.. 运行时间:不确定

Overall, I KINDA get the idea of it, but still not fully sure of how to use it in some situations. 总的来说,我很了解它,但是仍然不确定在某些情况下如何使用它。 Does anyone else also have a guide or some sort that gives examples and explanations of the time complexity of for loops and while loops? 是否还有其他人提供了有关for循环和while循环的时间复杂度的示例和说明的指南或某种指南?

the block of k is O(lg j) , where j is O(n) , so k is O(lg n) . k的块是O(lg j) ,其中j是O(n) ,所以k是O(lg n) but if you considering to whole program, it's O(n lg n) . 但是如果考虑整个程序,则为O(n lg n)

Here's the rules: 规则如下:

  • Loop is number of iterations times complexity of the body 循环是迭代次数乘以主体的复杂度
  • Consecutive blocks are sum of complexities 连续的块是复杂性的总和
    • But in O() only the asymptotically largest term is relevant, so you can immediately simplify to the higher complexity 但是在O()中,仅渐近最大项是相关的,因此您可以立即简化为更高的复杂度
  • Multiplicative constants are irrelevant 乘法常数无关
  • Geometric progression (the j loop with j = j * 2 and the k loop with k = k / 2 ) has complexity O(log n) 几何级数(在j循环与j = j * 2k带环k = k / 2 )具有复杂O(log n)

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

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