【问题标题】:the time complexity of array function数组函数的时间复杂度
【发布时间】:2017-04-23 19:11:03
【问题描述】:

我编写了一个函数来查找目标值应该插入给定数组中的位置。我们假设数组具有不同的值并按升序排序。我的解决方案必须是 O(log N) 时间复杂度

public static int FindPosition(int[] A, int target) {


    int a = A.length / 2;
    System.out.println(a);
    int count = a;
    for (int i = a; i < A.length && A[i] < target; i++) {
        count++;
    }
    for (int i = a; i > A.length && A[i] > target; i--) {
        count++;
    }
    return count;
}

这段代码的复杂度是否为 O(log N)?

【问题讨论】:

    标签: java arrays time-complexity


    【解决方案1】:

    简答

    没有。

    更长的答案

    随着您的索引中1 的增加,您不能指望有比O(n) 更好的解决方案。

    如果您的算法完全有效(我不认为它有效),它看起来需要O(n) 步骤。

    另外,您说您假设数组已排序,但无论如何您都对其进行了排序。所以你的代码是O(n*log(n))

    更重要的是,尝试对已经排序的数组进行排序对于某些排序算法来说是最坏的情况:它甚至可能是O(n**2)

    您正在寻找binary search

    【讨论】:

      【解决方案2】:

      不,这不是 nlogn

      public static int FindPosition(int[] A, int target){
      /*
      Time taken to sort these elements would depend on how
      sort function is implemented in java.  Arrays.sort has average 
      time complexity of Ω(n log n), and worst case of O(n^2)
      */
      Arrays.sort(A);
      
      
      /*Time taken to run this loop = O(length of A) or O(N) 
      where N = arraylength
      */
      
      for(int i=a;i<A.length&&A[i]<target;i++){
          count++;
      }
      /*Time taken to run this loop = O(length of A) or O(N) 
      where N = arraylength
      */
      for(int i=a;i>A.length&&A[i]>target;i--){
          count++;
      }
      return count;
      }
      

      现在时间复杂度将由以上三个中最长的一个来表示,因为分配和所有操作都是在恒定时间内完成的。

      因此在最坏的情况下使您的复杂度为 O(n^2)。

      【讨论】:

      • 很好的解释方式。
      • int count=0; for(int i=0;i
      • 时间复杂度将是循环重复的次数,在最坏的情况下,我们假设循环迭代直到最后一项,直到到达元素。所以它将是 O(A 的长度)
      • 所以如果有一个 (N x M) 的数组,时间复杂度将是 O(NxM)?这就是你说的。
      • 如果你有一个 n 行 m 列的二维数组,并且你遍历每一项,那么它就是 O(N*M)。这可能有用stackoverflow.com/questions/11032015/…
      猜你喜欢
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 2022-01-15
      • 2018-05-29
      相关资源
      最近更新 更多