在这些情况下是不同的?

时间:2017-09-13 14:48:05

标签: java big-o

在这两个不同的代码中(做同样的事情),bigO是不同的。 O(1)语句被更改但for循环保持不变,即运行次数相同?

 for (i=0;i<n;i++) {
    for (j=0;j<i;j++) {
         b+=i+i 
    } 
  }

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

不是两个代码都运行二次?

1 个答案:

答案 0 :(得分:1)

它们具有相同的O(n^2)复杂度。

两者都具有相同的结构:

for (i=0;i<n;i++) {
    // some constant amount of steps (without changing i or n), say p steps
    for (j=0;j<i;j++) {
         // another constant amount of steps (without changing i or j), say q steps
    } 
}

为了计算整体复杂性,让我们一步一步地计算步骤:

i = 0, so p steps on this stage
i = 1, j from 0 to 0, so (p + q) steps on this stage
...
i = k, j from 0 to k-1, so (p + q*k) steps on this stage
...
i = n-1, j from 0 to n-1, so (p + q*(n-1)) steps on this stage

总共{0}步,或BigO表示法中的p*n + q*n*(n-1)/2