Time complexity and space complexity analysis

time complexity

Time Complexity Myth:

  1. time complexity is not the time to run, but the number of executions algorithm statement.

  2. The algorithm not only refers to the name of the algorithm, a judge and a loop algorithms are counted.

Time complexity: number of algorithms statement is executed.

A number of executions of the algorithm ultimately statement may be expressed by a function f (n), as is the code, x algorithm is here ++ statements that f (n) = 10-x

    int x = 1;
    while(x < 10){
        x ++;
    }

N cycles two times f (n) = n ^ 2

i=1;
WHILE i<n DO
i=i*2

i once per cycle by the two, know when i> = n the end of the cycle, the cycle times m has 2 ^ m> = n, to obtain m = log2n.

 

 

Space complexity

Space complexity of the algorithm is in the process of running a temporary occupation of storage space, in other words, is to create the highest number of variables, how many times it has been created, then the space complexity of the algorithm is how much.

for(int i=0;i<n;++){
int temp = i;
}
和
int temp=0;
for(int i=0;i<n;i++){
temp = i;
}

The former space complexity is O (n), the latter space complexity is O (1) constant order. Well understood, the former once per cycle will re-create a temp objects, while the latter only outside the loop creates a temp objects, each cycle just give him a different reference only. So there is a law, if the algorithm statements have created objects, complexity and space complexity of this time of the algorithm is generally consistent, well understood, the algorithm is executed statement how many times the number of objects is created.

Guess you like

Origin www.cnblogs.com/2019go5/p/11414565.html