简体   繁体   中英

What is the time complexity for the following program?

How do I calculate the time complexity of the following program?

int[] vars = { 2, 4, 5, 6 };
int len = vars.length;
int[] result = new int[len];

for (int i = 0; i < len; i++) {
    int value = 1;

    for (int k = 0; k < i; k++) {
        value = value * vars[k];
    }
    for (int j = i + 1; j < len; j++) {
        value = value * vars[j];
    }

    result[i] = value;
}

and how is the above one same as below?

for (int i = 0; i < len; i++) {
    int value = 1;

    for (int j = 0; j < len; j++) {
        if(j != i) {
            value = value * vars[j];
        }
    }

    result[i] = value;
}

The i for loop is of time complexity O(n), because it performs one iteration for every element of the array. For every element in the array, you are looping through it once more -- half on average in the k for loop, and half on average in the j for loop. Each of these is O(n) as well. If there are 4 elements in the array, the number of operations is proportional to n*(n - 1), but in time-complexity, constants such as the 1 are ignored.

The number of operations your method will perform is proportional to the number of elements in it multiplied by itself, therefore, overall, the method is O(n 2 ).

For the first fragment:

在此输入图像描述

For the second fragment:

在此输入图像描述

A general approach in determining the complexity is counting the iterations. In your example, you have an outer for loop with two loops nested in it. Note: Instead of len, I'll write n. The outer loop

for (int i = 0; i < n; i++)

iterates n -times. The number of iterations of the two next loops are actually more easy to count, than it looks like: The second loop iterates i -times and the third ni -times. If you add them together you get n -many iterations within the outer loop.

Finally, if the outer loop does n iterations and within each of these iteration the code loops another n times you get the result of n^2 iterations. In the traditional notation of complexity-theory you'd write, that the algorithm has an upper-bound of n^2 or is in O(n) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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