【问题标题】:Big-O analysis with functions within functions函数内函数的 Big-O 分析
【发布时间】:2011-11-20 16:14:05
【问题描述】:

在处理函数中的函数时(分析最坏情况时),我对 Big-O 的工作方式感到困惑。例如,如果你有类似的东西怎么办:

for(int a = 0; a < n; a++)
{
    *some function that runs in O(n*log(n))*
    for(int b = 0; b < n; b++)
    {
        *do something in constant time*
    }
}

整个块是否会在 O(n^2*log(n)) 中运行,因为在第一个 for 循环中,你有一个 O(n) 和一个 O(n*log(n)),所以 O( n*log(n)) 更大,因此我们采用那个?还是因为在外部 for 循环中有一个 O(n) 和一个 O(n*log(n)) ,所以它是 O(n^3*log(n))?

感谢任何帮助!谢谢!

【问题讨论】:

    标签: performance algorithm big-o


    【解决方案1】:

    这是

    O(N) * (O(N lg N) + O(N) * O(1)) = O(N) * (O(N lg N) + O(N))
                                     = O(N) * O(N lg N)
                                     = O(N^2 lg N)
    

    因为您有 O(N) 函数的 O(N) 迭代和 O(N) 恒定时间操作。 O(N lg N) + O(N) 简化为 O(N lg N),因为 O(N lg N) &gt; O(N)

    【讨论】:

      【解决方案2】:

      在计算这种类型的复杂性时,您应该添加内联或顺序函数和乘法嵌套函数。

      例如,这将是O(n):

      // O(n) + O(n) = O(2n)` which is `O(n)` (as constants are removed)
      for (int i = 0; i < n; i++)
      { 
          /* something constant */ 
      }
      for (int j = 0; j < n; j++)
      { 
          /* something constant */ 
      }
      

      但是当函数嵌套时,复杂度会成倍增加:

      // O(n) * O(n) = O(n^2)
      for (int i = 0; i < n; i++)
      { 
          for (int j = 0; j < n; j++)
          { 
              /* something constant */ 
          }
      }
      

      您的示例是一个组合 - 您在另一个函数中嵌套了一些顺序操作。

      // this is O(n*logn) + O(n), which is O(n*logn)
      *some function that runs in O(n*log(n))*
      for(int b = 0; b < n; b++)
      {
          *do something in constant time*
      }
      
      // multiplying this complexity by O(n)
      // O(n) * O(n*logn)
      for(int a = 0; a < n; a++)
      {
          // your O(n*logn)
          // your b loop
      }
      

      【讨论】:

      • +1 即使在另一个答案被接受后也能得到清晰的解释。
      • 这也是一个很好的答案!谢谢!
      猜你喜欢
      • 2022-09-25
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      相关资源
      最近更新 更多