【问题标题】:What is the complexity of this program?这个程序的复杂性是什么?
【发布时间】:2015-02-18 11:13:56
【问题描述】:

我想分析下面程序的执行时间复杂度。 请用解释回答。

private static void printSecondLargest(int[] arr) {
    int length = arr.length, temp;
    for (int i = 0; i < 2; i++) {
        for (int j = i+1; j < length; j++) {
            if(arr[i]<arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    System.out.println("Second largest is: "+arr[1]);
}

【问题讨论】:

  • 内部循环运行(2* arr.length)-2完全。复杂度为O(n)
  • O(n) 是程序的复杂度。
  • @TheLostMind 感谢您的回答。但是你的答案是正确的,但解释有点不正确。它会执行 (2* arr.length) - 3 次。
  • @RahulChaubey - 没错。 1 +2 --> 3.. :)

标签: java algorithm data-structures big-o asymptotic-complexity


【解决方案1】:

是 O(n),其中 n 表示数组的长度。

最内层循环的主体:

if(arr[i]<arr[j]) {
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

以恒定的时间运行。

此代码将首先执行arr.length-1 次,然后是arr.length-2 次。那是2 * arr.length - 3。因此执行时间与 2n-3 成正比,即 O(n)。

【讨论】:

  • 你是怎么得到 4n 的?两次处决 = 2n?
  • 谢谢aioobe。你知道用 C 解决它的更好方法吗?
  • 你不能比 O(n) 做得更好,但请参阅 this question 以了解替代实现。另外,请阅读this
  • @bigdestroyer,代码不会执行 (2*n -3) 两次。第一次是 n-1,第二次是 n-2,所以总共 n-1 + n-2 = 2n-3。
【解决方案2】:

显然是 O(n)。外循环仅运行 2 次,内循环运行 N 次。因此,总体复杂度为 O(2*n)。

【讨论】:

    【解决方案3】:

    外循环将运行两次,内循环运行 (length-1) 和第二次 (length-2)

    假设长度为N

    so it will be 2*((N-1)/2+(N-2/)2)==2*(2n-3)/2

    Which is final (2N-3) and in O notation it is O(N)
    

    【讨论】:

    • (N-2/)2? /2 是从哪里来的?
    • N-1/2和N-2/2的常用LCM:-)
    • 是的,两次内部迭代的平均值
    • 但是平均是完全多余的。您必须汇总所有运行时,而不是平均它们。
    • 实际上我在初始步骤中使用了 2*,它表示循环的迭代次数,所以我必须取所有时间消耗的平均值 :-) 抱歉,是的,它是多余的:- )
    【解决方案4】:
    private static void printSecondLargest(int[] arr) {    
        int length = arr.length, temp;    // **it takes contant time**
        for (int i = 0; i < 2; i++) {     // as loop goes only two step it also takes constant time
            for (int j = i+1; j < length; j++) {   // this loop takes n time if we consider arr length of size n
                if(arr[i]<arr[j]) {
                    temp = arr[i];    // it also takes constant time
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        System.out.println("Second largest is: "+arr[1]);
    }
    

    因此,根据上述计算,我们忽略恒定时间并计算所有变化的时间约束,并且根据代码复杂度将为O(n)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 2014-08-06
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多