【问题标题】:runtime of a block code块代码的运行时间
【发布时间】:2013-03-10 14:04:54
【问题描述】:

谁能解释一下为什么这段代码的运行时复杂度 T(n) 为 2lgn+2。我认为应该是lgn+2。

public static reduce(int n){
 int result = 0;
 while (n >1){
   n = n/2;
   result = result +1;
 }
 return result;
} 

【问题讨论】:

  • 嗯,这取决于你分配给每一行代码的复杂度......

标签: runtime complexity-theory


【解决方案1】:

假设每行需要 1 个单位的时间(不包括 n > 1 检查)。

所以int result = 0;n = n/2;result = result +1;return result; 分别归类为花费 1 个单位时间。

2 来自int result = 0;return result;,每个都执行一次。

2 log2n 来自n = n/2;result = result +1; 每个被执行 log2n 次。

注意:

n > 1 也可以归类为时间单位,得到 3 log2n + 2。

n = n/2;result = result +1; 可以分别归类为花费 2 个单位的时间,导致(使用上述)5 log2n + 2。

这都是非常主观的。

对于某些 c 和 d,唯一的全面协议是 c log2n + d。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 1970-01-01
  • 2012-06-19
  • 2020-04-18
相关资源
最近更新 更多