简体   繁体   English

下面 3 个嵌套循环的时间复杂度是多少?

[英]What is the Time Complexity for the 3 nested loops below?

Here's the code:这是代码:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n * n; j++) {
        for (int k = 0; k < j; k++) {
            sum++;
        }
    }
}

I need to evaluate the Time complexity in Big-O notation of the nested loops above.我需要评估上面嵌套循环的 Big-O 表示法的时间复杂度。

Is it just O(n) * O(n) * O(n) + O(1) to make O(n^3) ?是否只是O(n) * O(n) * O(n) + O(1)才能生成O(n^3) Or is there more to it?或者还有更多吗?

The most inner loop is executed in quadratic time (not constant), hence it should be O(n) * O(n^2) * O(n^2) = O(n^5) .最内层循环以二次时间(不是常数)执行,因此它应该是O(n) * O(n^2) * O(n^2) = O(n^5)

Here are all the costs:以下是所有费用:

  • Most outer loop - O(n)最外层循环 - O(n)

  • The second loop - O(n^2) for each element for the outer loop第二个循环 - 外循环的每个元素的O(n^2)

  • The most inner loop - O(n^2) for each element for the second loop最内层循环 - 第二个循环的每个元素的O(n^2)

for (int i = 0; i < n; i++) -> runs n times.
 for (int j = 0; j < n * n; j++) -> runs n² times.
  for (int k = 0; k < j; k++) -> runs n² times (k == j == n²)

n * n² * n² = n^5.

sum+++ is an operation of constant runtime (1) and can therefore be ignored. sum+++ 是常量运行时间 (1) 的操作,因此可以忽略。

The second loop isn't O(n) , it's O(n^2) by itself.第二个循环不是O(n) ,它本身就是O(n^2)

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

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