【问题标题】:Running Time of Nested Loops, When inner loop false,嵌套循环的运行时间,当内部循环为假时,
【发布时间】:2021-11-28 18:41:49
【问题描述】:

01.) 考虑增长时间,当嵌套循环的内循环为假时,它的增长时间是O(n)吗? 例如:

for (int i=0; i<n; i++){    
    for (int j=0; j>n; i++){
        //some code
    }
}

02.) 考虑到增长时间,当嵌套循环的内循环有另一个数组长度变量为'm'时,它的增长时间是O(n m)吗? 例如:

for (int i=0; i<n; i++){    
    for (int j=0; j<m; i++){
        //some code
    }
}
  1. 以下代码的运行时间是多少? (请用步骤说明)
for (int i = 0; i < n; i++) {                  
   for (int j = 0; j > n; j++) {               
      for (int k = 0; k > n; k++) {            
         System.out.println("*");   
      }
   }
}

谢谢。

【问题讨论】:

  • 你能澄清一下“增长时间”和“循环是假的”是什么意思吗?
  • 我认为loop is false表示循环的条件将始终为false,无论输入大小如何。所以我们可以简单地忽略那个循环。 growth time 表示time complexity 我猜。
  • 我的解决方案对@Anonymous 有帮助吗?

标签: performance time time-complexity big-o


【解决方案1】:
  1. 是的,如果绝对清楚由于条件为false 而不会执行内部循环,而不管输入大小如何,那么时间复杂度将为O(n)
  2. 是的,下面有详细的分析。但是,我假设您在内部循环中错误地增加了 i
for (int i=0; i<n; i++){    
    for (int j=0; j<m; j++){   // j++
        //some code
    }
}
number of operations performed by inner loop in each iteration of outer loop : m
number of operations performed by outer loop : n
Total number of operations : n*m
Time complexity f(n) ∈ O(n*m)

如果您发布的代码没有错误,则时间复杂度分析:

for (int i=0; i<n; i++){    
    for (int j=0; j<m; i++){
        //some code
    }
}
j=0 --> j<m  (i++)
If 0<m, then it is an infinite loop. It's pointless to make a time complexity analysis. 
If 0>=m, then inner loop is not going to be executed, therefore time complexity will be O(n).
  1. 详细分析:
for (int i = 0; i < n; i++) {           // n many times
   for (int j = 0; j > n; j++) {        // n many times       
      for (int k = 0; k > n; k++) {     // n many times         
         System.out.println("*");   
      }
   }
}
All of the loops are iterated n many times. Most-inner loop will perform n operations. Outer loop will perform n, which makes n*n. And most-outer loop will perform n operations, which makes n*n*n in total.
Time complexity f(n) ∈ O(n^3)

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 2021-05-07
    相关资源
    最近更新 更多