时间复杂性审查

时间:2015-12-04 20:38:39

标签: time big-o time-complexity

以下代码段的时间复杂度是多少?

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}}?

2 个答案:

答案 0 :(得分:2)

是的,复杂性将是O(n 2 )。

如何吗

  • 一半次(即n / 2次),你将遍历n个元素=(n / 2)* n = n 2 / 2.
  • 一半次(再次,n / 2次),你将只有一个要迭代的元素=(n / 2)* 1 = n / 2.
  • 因此,整体复杂度= O(n 2 / 2 + n / 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).