【问题标题】:calculate time complexity of nested for loops计算嵌套for循环的时间复杂度
【发布时间】:2013-10-13 05:25:33
【问题描述】:

我无法计算这些 for 循环的时间复杂度:

for(int i=0; i<len; i++){
    countOne++;
    for(int j=i/2; j<len; j++){
        countTwo++;
        for(int k=i/2; k<len; k++){
            countThree++;
        }
    }
}

我不明白如何计算 2 个最内层循环的时间复杂度。

【问题讨论】:

  • “计算运行时间”究竟是什么意思?
  • 我想你想计算复杂度 Big O ?对吗?
  • 是的,Big O 运行时间。我想知道每一行的运行时间,特别是 2 个内部循环。例如,我相信第一个 for 循环会运行 n+1 次。
  • @AdrienneKeck 我认为您要查找的术语是time complexity,而不是运行时间(通常称为run time)。无法计算代码的运行时间,因为这取决于无限多的附加因素。

标签: performance algorithm big-o


【解决方案1】:

这听起来像是一个大问题。但是您应该在将来指定。

  • countOne 递增 len 倍。
  • 对于每个icountTwo 增加len-i/2 倍。 i 从 0 到 len-1,所以 countTwolen/2len 之间递增(或 O(len)) 倍 i 或 O(len2 ) 总数。
  • countThree 的类似情况,增加了 O(len3) 次。

因此整个算法是O(len3)。

【讨论】:

    【解决方案2】:

    您有条不紊地使用 Sigma 表示法:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2021-12-24
      相关资源
      最近更新 更多