繁体   English   中英

确定Java代码的时间复杂度

[英]Determining the time complexity of Java code

我正在研究 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)?

当我想到在最坏的情况下,我的 function 会在数组的整个长度上前后移动,但这只会在我的 int x for 循环中发生一次,所以我不确定是否时间复杂度是 O(n) 线性时间或 O(n^2) n 平方。

谢谢

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM