以下代码段的时间复杂度是多少?
int[][] A = new int [n][];
for (int i=0; i<n; i++) {
if (i % 2 == 0) // i is a multiple of 2
A[i] = new int [n];
else
A[i] = new int [1];
}
for (int i=0; i<A.length; i++)
for (int j=0; j<A[i].length; j++)
sum = sum + A[i][j];
我理解第一个循环循环n次,然后,将有n/2
行长度为n的矩阵,n/2
长度为1.总时间为{{ 1}}?
答案 0 :(得分:2)
是的,复杂性将是O(n 2 )。
如何吗
答案 1 :(得分:0)
Well firstly let's decide with terminology. For example, let's put that every single operation will be to equal to 1
. Let's take your code (just to be consistent - we will call this method) and go line by line.
int[][] A = new int [n][];
this will be equal to 1
.
for (int i=0; i<n; i++) {
Here we have loop and in worst case it will be n
.
if (i % 2 == 0) // 1
A[i] = new int [n]; // 1
else
A[i] = new int [1]; // 1
}
Above operation could be counted as 1
each.
for (int i=0; i<A.length; i++)
Loop is equal to n
-elements.
for (int j=0; j<A[i].length; j++)
Inner loop is the same n
.
sum = sum + A[i][j];
Again this will be equal to 1
.
Inner loops are multiplied so you are correct, but take into account that this will be exactly big-O notation O(n2).