【问题标题】:Is my understanding of big-O correct for these Java functions incorrect?对于这些 Java 函数,我对 big-O 的理解是否正确?
【发布时间】:2017-03-15 16:10:15
【问题描述】:

我的方法(可能不正确)是公式化的。如果有一个循环那么 (n+1) 如果有一个嵌套循环 (n^2) 如果一个语句那么 O(1)。如果除法则 log(n)。

这里有一些例子和我解决的理由,完全不确定这种方法是否有问题,或者其中任何一个是否正确。我需要这方面的帮助。

示例 1:

i = n; // I think O(1) because it's a statment
while (i > 1) // I think O(n) because it's a loop
  i = i/4; // O(n) because it's in a loop and log_4(n) b/c division
// I think Overall if we combine the O(n) from earlier and the log_4(n)
// Therefore, I think overall O(nlog(n))

示例 2:

for (i = 1; i < n; i = i + i) //  I think this is O(n+1) thus, O(n)
  System.out.println("Hello World"); // O(n) because it's in a loop
// Therefore, overall I think O(n)

示例 3:

for (i = 0; i < n; i = i + 1) // I think O(n+1), thus O(n)
  for (j = 1; j < n; j++) // I think O(n^2) because in a nested loop
    System.out.println("Hello Universe!"); // O(n^2) because in a nested
  // Therefore, overall I think O(n^2)

示例 4:

for (i = 1; i < (n * n + 3 * n + 17) / 4; i = i + 1) // O((20+n^3)/4) thus, O(n^3)
  System.out.println("Hello Again!'); // O(n) because it's in a loop
// Therefore, overall I think O(n^3) because largest Big-O in the code

谢谢

【问题讨论】:

  • 检查每个循环执行了多少次迭代,并将其与n 的值进行比较(如果您是视觉学习者,可以制作一个表格)。看看这两个数字之间的关系应该会给你一个提示。

标签: performance loops big-o asymptotic-complexity


【解决方案1】:

示例 1:您的结果是错误的。因为循环发生 log_4(n) 次并且除法需要 O(1) (除以 4 只需要按位移位)。因此总时间只有 O(log(n))

Example2:这也是错误的。在每次迭代中,您都复制循环变量。所以循环发生 O(log(n)) 次。打印命令耗时 O(1),总时间为 O(log(n))。

示例 3:您的答案是正确的。因为你有两个嵌套的 O(n) 循环。请注意,此循环与前面的两个示例不同。

示例 4:我认为你写错了。 ((n * n + 3 * n + 17) / 4) 是否等于 O((20+n^3)/4)???它是 O(n^2)。因此,根据我之前的解释,总时间是O(n^2)。

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多