【问题标题】:Explaining why this algorithm is n^2 [duplicate]解释为什么这个算法是 n^2 [重复]
【发布时间】:2018-09-30 10:13:17
【问题描述】:

我在论证这段代码的运行时间时遇到了一些麻烦。我知道代码以 O(n^2) 运行,但有人告诉我解释为什么会这样。我想我需要对其进行一些计算,但我被卡住了。 我需要弄清楚的算法(伪代码)是。

    count = 0                        1
    for i = 0 to n-2                 n
        for j = 1 to n               n^2
            if A[j]<A[i]             1
                count = count + 1    1

我也写了我认为的每一行的运行时间。但是,我不知道这是否正确。

【问题讨论】:

  • 什么让你困惑?
  • 有人告诉我解释为什么算法以 O(n^2) 运行。所以让我感到困惑的是我应该如何写它,我如何从我所拥有的答案到 O(n^2)

标签: algorithm time runtime time-complexity


【解决方案1】:

外部for循环从0遍历到n-2

去掉外循环中的常量,我们可以说它会循环n次。 对于外循环中 [0..n-2] 范围内的每个数字,内循环从 [1..n] 开始迭代

if i=0, inner loop runs from 1 to n,
if i=1, inner loop runs from 1 to n,
.
.
.
till  i=n-2, inner loop runs from 1 to n,

所以时间复杂度将是 (外循环 * 内循环) = O(n*n)O(n^2)

【讨论】:

    【解决方案2】:

    外部for 循环精确地迭代n-1 = O(n) 次。在外部for 循环的每次迭代中,内部for 循环精确地迭代n = O(n) 次,因此总体上它迭代O(n^2) 次。内部循环内完成的工作是恒定时间O(1)。因此,总体时间复杂度为O(n^2),因为我们重复了O(1) 工作量O(n^2) 次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2020-12-16
      相关资源
      最近更新 更多