【发布时间】:2019-09-29 16:58:05
【问题描述】:
所以我很难理解大 O 符号,并且正在寻找一些示例来更好地理解它。现在让我们看看下面的代码:
`public static void main(String[] args)` {
int N = 4;
int sum = 0;
for (int i = 1; i < N; i = i*2)
{
for (int j = 1; j < N; j++)
{
sum++;
}
}
Am i assuming correctly that the Big O Notation here would be: O(N log(N))? Because the first for loop runs log(n) times and the second one does N times? If not: What would be the correct Big O Notation here?
And another example:
`public static int f(int N){
if (N<=1)
{
return 0;
}
return (2*f(N/2));
}`
这里的大 O 符号是什么?是 O(log N) 吗?
正如您所看到的,我猜了一点,所以如果您对如何识别正确的大 O 表示法有任何建议,我将非常感激!
【问题讨论】:
-
1.
O(NlogN)2.O(logN) -
第二种情况,智能编译器会让程序立即返回0
-
@BorisBorovski "时间到 n / 2" 不正确。
i将是 1, 2, 4, 8, 16, 32, ... 所以它会迭代log₂(n)次,而不是n / 2次。 -
@BorisBorovski 如果 n = 100,循环将在 64 处结束,经过 7 次迭代。
log₂(100) + 1= 7.64 ≈ 7. --- 如果 n = 10000,循环将在 8192 处结束,经过 14 次迭代。log₂(10000) + 1= 14.29 ≈ 14.
标签: java performance runtime big-o theory