【问题标题】:What Big O notation do i have here?我在这里有什么大 O 符号?
【发布时间】: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


【解决方案1】:

你对第一种情况是正确的,你的推理是正确的。

确实,第二种情况的复杂度是 O(logn)。这是一种思考方式:

在递归的每一步中,您都将数字除以 2,直到达到 1 的基本情况。因此,调用此函数的次数是您可以将数字除以 2 直到达到 1 的次数,根据定义,这恰好是 log(n)。 每次调用该函数时都会执行 O(1) 次操作,因此总复杂度为 O(logn)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2020-09-12
    • 2011-04-22
    相关资源
    最近更新 更多