我的方法(可能不正确)是公式化的。如果有一个循环那么(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
谢谢
答案 0 :(得分:0)
示例1:您的结果是错误的。因为循环发生log_4(n)次并且除法取O(1)(除以4只需要按位移位)。因此总时间仅为O(log(n))
示例2:这也是错误的。在每次迭代中,您复制循环变量。所以循环发生O(log(n))次。 print命令取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)。