【问题标题】:Determining the time complexity of Java code确定 Java 代码的时间复杂度
【发布时间】:2022-01-27 06:41:49
【问题描述】:

我正在研究一个 Java 练习面试问题,以查找连续子数组的数量。我有一个可行的解决方案,只是想确保我了解我的答案的时间复杂度:

  //solution is called with array of n length like this:
    countSubarrays([3,4,1,6,2])

  int[] countSubarrays(int[] arr) {
    System.out.println(Arrays.toString(arr));
    
    int[] ret = new int[arr.length];
    //for each index:
    for(int x = 0; x < arr.length; x++){
      int max = arr[x];
      System.out.println("arr["+x+"]="+max);
      
      //try going forward
      List<Integer> forwardList = new ArrayList<Integer>();
      for(int y = x; y < arr.length; y++){
        if(arr[y] <= max){
          forwardList.add(arr[y]);
        }else{
          break;
        }
      }
      System.out.println("forwardList="+forwardList);
      
      //try going backwards
      List<Integer> backwardList = new ArrayList<Integer>();
      for(int y = x; y >= 0; y--){
        if(arr[y] <= max){
          //add to start of list
          backwardList.add(0, arr[y]);
        }else{
          break;
        }
      }
      System.out.println("backwardList="+backwardList);
      
      //count number of contiguous subarrays
      int count = (forwardList.size() + backwardList.size()) -1;
      ret[x]=count;
      System.out.println("count: "+count+"\n");
    }

      return ret;
  }

如果输入数组的长度为 n,并且我的代码解决方案具有一个从 0 到 n ( int x ) 计数的 for 循环,以及两个嵌套的 for 循环向前和向后计数,直到找到更大的 int,这样意思是我的函数时间复杂度是 O(n^2)?

我想到这个解决方案时认为在最坏的情况下,我的函数会前后移动整个数组长度,但这只会在我的 int x for 循环中发生一次,所以我没有确定时间复杂度是 O(n) 线性时间还是 O(n^2) n 平方。

谢谢

【问题讨论】:

  • 你的问题是时间复杂度是O(n)还是O(n^2)

标签: java arrays time-complexity big-o contiguous


【解决方案1】:

此代码的简化时间复杂度为 O(n^2),其中 n 是数组的大小。这是因为您正在迭代 2 * (1 + 2 + ... + n) 次。 (有一个 2 因为你在第一个循环中有 2 个 for 循环)。这将是 O(2n(n-1)/2) = O(n*(n-1)),简化为 O(n^2)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2018-07-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多