【发布时间】: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