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(n2).

其他提示

For the first fragment:

enter image description here

For the second fragment:

enter image description here

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 n-i-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).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top