what
方法的时间复杂度为O(n^2),它使用的方法f
的时间复杂程度为O(n)。我需要计算方法what
的总体时间复杂性。我是否也考虑了方法f
的时间复杂性,因此总体上方法what
的时间复杂性将为O(n^2*n=n^3),或者每个方法都考虑了自己的时间复杂性?因此在这种情况下,方法what
将保持在时间复杂性O(n^2)?
private static int f (int[]a, int low, int high)
{
int res = 0;
for (int i=low; i<=high; i++)
res += a[i];
return res;
}
public static int what (int []a)
{
int temp = 0;
for (int i=0; i<a.length; i++)
{
for (int j=i; j<a.length; j++)
{
int c = f(a, i, j);
if (c%2 == 0)
{
if (j-i+1 > temp)
temp = j-i+1;
}
}
}
return temp;
}
时间复杂性提供了执行所需时间的高级估计。所以Yes
需要包含每一行需要时间的代码,即f
函数的时间复杂性。这也需要时间。
CCD_ 9函数在CCD_ 10函数内部有两个循环和一个循环,CCD_。
Let calculate Time Complexity
f
函数的时间复杂度,当它是"what"函数的第一次时,当i=0,j由内环从0增加到n
1. When i=0 and j=0 then execute one time
2. when i=0 and j=1 then execute two time
3. when i=0 and j=2 then execute three time
soon on
.
.
.
n. When i=0 and j=n then execute n time
SO
Total = 1+ 2+3+4.......+n
= n(n+1)/2 = sum of n consecutive numbers
Thus
TC of `f` Function execute first time from J loop from 0 t0 n =n(n+1)/2
但是i
循环执行n次,所以
Total Time Complexity of whole execution/ your program equalvent to n*[n*(n+1)/2 + ((n-1)n)/2) + ((n-2)(n-1))/2+ ...... + 1] ~ that means TC equlavent to
O(n^3)