[英]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. i
for
循环具有时间复杂度O(n),因为它对数组的每个元素执行一次迭代。 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. 对于数组中的每个元素,您再次循环遍历 - 在
k
for
循环中平均for
一半,在j
for
循环中平均for
一半。 Each of these is O(n)
as well. 这些中的每一个也是
O(n)
。 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. 如果数组中有4个元素,则操作数与n *(n - 1)成比例,但在时间复杂度上,忽略常量(如
1
。
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 ). 您的方法将执行的操作数量与其中的元素数量成正比,因此,总体而言,该方法为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.
在您的示例中,您有一个外部for循环,其中嵌套了两个循环。 Note: Instead of len, I'll write n.
注意:我会写n而不是len。 The outer loop
外循环
for (int i = 0; i < n; i++)
iterates n
-times. 迭代
n
。 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. 两个下一个循环的迭代次数实际上比它看起来更容易计数:第二个循环迭代
i
和第三次ni
。 If you add them together you get n
-many iterations within the outer loop. 如果将它们一起添加,则在外部循环中进行
n
次迭代。
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. 最后,如果外部循环执行
n
次迭代并且在每次迭代中,代码循环另外n
次,则得到n^2
次迭代的结果。 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)
. 在您编写的复杂性理论的传统表示法中,算法的上限为
n^2
或者为O(n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.