time complexity
Used to represent, the time it takes for an algorithm to solve a problem of size n.
Comprehension: Measured by the number of times the same code block is executed
sum = n*(n+1)/2; //顺序执行时,此代码块只会运行一次因此时间复杂度为 O(1)
for(int i = 0; i < n; i++){
printf("%d ",i); //根据上面的理解它的时间复杂度O(n)
}
Sometimes approximate values are taken for convenience, such as:
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%d ",i); //准确的时间复杂度为O(n^2)
}
}
but
for(int i = 0; i < n; i++){
for(int j = i; j < n; j++){
printf("%d ",i);//此代码块运行次数为 (1+n)*n/2
//由高数中的极限可推n无限大时,(1+n)*n/2极限为n^2,因此时间复杂度O(n^2)
}
}
How does log 2 n appear?
int i = 1, n = 100;
while(i < n){
i = i * 2; //设执行次数为x。 2^x = n 即x = log_2 n,时间复杂度O(log2n)
//当循环步数不为1跳跃时,便会产生多种答案
}
Reference Time Complexity and Space Complexity
space complexity
Used to represent, the space consumed by an algorithm to solve a problem of size n.
Comprehension: amount of extra space to generate (temporary variables included)
public static void swap(int a, int b) {
int temp = a;
a = b;
b =temp;
}
A simple exchange is completed with the help of a temporary variable temp, so the space complexity is O(1)
public static void swap(int a, int b) {
a = a+b;
b = a-b;
a = a-b;
}
And using addition and subtraction swap will not generate temporary variables so the space complexity is O(0)