Complexity of Time:
1 Find the basic statement: the most executed statement in the algorithm is the basic statement, usually the most inner loop of many loops.
2 Calculate the order of magnitude of the base statement:
You only need to calculate the number of executions of the base statement. Ensure that the highest power is correct.
Ignore the coefficients of the lower power and the highest power, simplify the analysis, and focus on the most important point: growth rate.
3 The performance of the algorithm is represented by the large O notation.
The number of algorithms for basic statement executions is placed in the large O-notation.
Example:
- The time complexity of a simple statement is O (1)
- The time complexity of a loop is O (n)
for (int i = 1; i <=n; i++) {count++}
- The time complexity is O (log2 N) loop statement, the efficiency is particularly high
for (int i = 1; i <=n; i*=2) {count++}
1 2 4 8 16 32 2^30 = 1024*1024*1024=1000*1000*1000=10 billion i*=2 O (log 2 1 billion) 30 times, i++ O (1 billion) cycle required 1 billion times, log 2 n efficiency >> ; n
- A double cycle with a time complexity of O (n^2)
for (int i = 1; i <=n; i++)
for (int j = 1; j<=i; j + +)
count++;
- The time complexity is O (nlog2 N) of the double cycle:
for (int i = 1; i <=n; i*=2)
for (int j = 1; j<=n; j + +)
count++; Inner Loop n times, outer loop log2 n times, O (n*log2 N)
- The time complexity is O (N2) of the double cycle:
for (int i = 1; i <=n; i++)
for (int j = 1; j<=i; j + +)
count++; Outer Loop n times, Inner loop indeterminate t (n) = 1+2+3+4+......+n= (1+n) n/2,o (n^2)
Spatial complexity (space):
See the number of variables. Generally speaking is S (1).
Recursive algorithm each call itself to allocate space, space complexity is higher.
Advantages and disadvantages of recursion: inefficient, occupy more space. Simple code, simple thinking.
Two time complexity and space complexity