【发布时间】: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