(1) Time complexity:
see the example below
for(i = 0; i < n; ++i)1
for(j = 1; j < n; j++)2
{c[i][j]=0;} 3
Statement 1 execution times: 1+n+n=2n+1;
Number of executions of statement 2: n* (1+n+n)=n*(2n+1)=2n^2+n;
Statement 3 execution times: double loop n^2;
Total f(n)=2n+1+2n^2+n+n^2=3*n^2+3n+1--->O(n^2)
The calculation speed of the computer is very fast, hundreds of millions of times a second, so the low-order terms and coefficients are not considered.
The time complexity follows:
1. Only high-order items are retained, and low-order items are discarded directly
2. No coefficient
Exercise 1: {++x;s = 0;} O( 1 )
3. The number of executions is constant and is O(1)
Exercise 2:
for(i = 2; i< n; ++i)
for(j = 2; j < i-1;++j)
{++x; a[i][j]=x;}
Although the core statement has two sentences, the calculation coefficient of the time complexity is not required, so the time complexity is O( n^2 )
Exercise 3:
for(int i = 0;i < n;i++);
The variation of i is: 1 2 3 4 ... n
So the time complexity is O( n )
Exercise 4:
for(int i = 0;i < n; i *= 2)
The variation of i is: 1 2 4 8 ...n
2^x=n--->x = log to the nth power of the base 2 (can't be typed here ) time complexity O(log to the nth power of the base 2)
Exercise 5:
int Age(int n)
{
if(n==1)
{
return 10;
}
return Age(n-1) + 2;
}
This is a recursive problem: for example, to find n = 5, use Age(5)-->Age(4)-->Age(3)-->Age(2)-->Age(1), and then return Age (5)<--Age(4)<--Age(3)<--Age(2)<--Age(1), it needs to be counted twice, which is twice the relationship, but the calculation coefficient of the time complexity No, so the time complexity is O(n)
(2) Space complexity: the relationship between the additional auxiliary space required to implement the algorithm and the problem
Exercise 1: {++x;s = 0;}
Space Complexity: O( 1 )
Exercise 2:
for(i = 2; i< n; ++i)
for(j = 2; j < i-1;++j)
{++x; a[i][j]=x;}
Space Complexity: O( 1 )
Exercise 3:
for(int i = 0;i < n;i++);
Space Complexity: O( 1 )
Exercise 4:
for(int i = 0;i < n; i *= 2)
Space Complexity: O( 1 )
Exercise 5:
int Age(int n)
{
if(n==1)
{
return 10;
}
return Age(n-1) + 2;
}
Space complexity: O( n ), the space will not be released when recursively called, but gradually released when returning.There are two ways to return the Fibonacci sequence: loop and recursion. Let's use time complexity and space complexity to explain why recursion is not very good.
int Fabio1(int n)//loop,
{int f1 = 1;
int f2 = 1;
int f3 = 1;
for(int i=2;i<n;i++)
{
f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f3;
}
时间复杂度O(n),空间复杂度O(1)
int Fabio(int n)//递归
{
if(n==1 || n==2)
{
return 1;
}
return Fabio(n-1) + Fabio(n-2);
}
时间复杂度O(2^n ),空间复杂度O(n),相较于循环的写法递归的空间复杂度较大,因为栈一般的大小为1M,当n较大时,容易出现栈溢出,所以用递归的写法并不是特别好。