【问题标题】:Time complexity of Big O notationBig O 表示法的时间复杂度
【发布时间】:2020-04-28 22:04:59
【问题描述】:

我需要找出某个函数的时间复杂度,但我不确定我是否正确。

让我们看看:

f(int i){
    Int x = 1;
    While(x > i){
        System.out.println(x);
        x=x*2;
    }

    While(x > 2){
        x = (int) Math.pow(x,1/2);
        System.out.println(x);
    }
}

现在,我认为第一个 while 循环告诉我们 x = log(i);

第二个循环依赖于x,她在每次迭代中取x的值:

x^1/2 + x^1/4 + ••• + x^1/(2^k)。

假设第二个循环在 x

(Log(i))^1/(2^k) 和对数规则后我们发现是 O(loglog(n))

【问题讨论】:

  • 第一个循环是无限的或永远不会运行。你依赖溢出吗?
  • @afghanimah 我认为 OP 的意思是 while(x < i)
  • @rtx13 如果是这样,我支持你的回答
  • @afghanimah 你说得对,while 循环是 (x

标签: data-structures big-o


【解决方案1】:

假设第一个循环是while(x < 1)

  • 第一个循环是log(n)
  • 第二个循环是log(log(n))

第一个循环占主导地位,所以我会说函数 f() 具有 log(n) 复杂性。

【讨论】:

  • 第二个循环依赖第一个循环没关系?正因为如此,我需要忽略第一个循环?
  • 不,当你把复杂度加起来时,O(logn) + O(loglogn),你可以放弃 O(loglogn),因为 O(logn) 占主导地位。就像你有 O(n) + O(logn),但你可以放弃 O(logn)。尝试将其绘制成图表或计算每个循环对某些输入执行了多少次循环以了解情况。
猜你喜欢
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2011-04-23
相关资源
最近更新 更多