Data Structure - time complexity / space complexity

Data Structure - time complexity / space complexity

A), Complexity:

Complexity: also known as progressive complexity .

Category : 1) time complexity.

2) spatial complexity.

Time complexity: T (n-) = O (F (n-)), the number of times that the implementation of the code is proportional to the execution time and code.

T (n): the execution time code.

f (n): number of code execution.

n: the size of data.

O: trends execution time and code size of data growth.

B) the time complexity analysis:

1), only concerned with the number of cycles up to a short code

T(n) = O(n)

 int cal(int n) {
   int sum = 0;
   int i = 1;
   for (; i <= n; ++i) {
     sum = sum + i;
   }
   return sum;
 }

2), addition rule, T (n) = O (max (f (n), g (n)))

Scene: a plurality of cycles: T (n-) = O (MAC (F (n-) + G (n-^ 2))) = O (^ n-2)

int cal(int n) {
   int sum_1 = 0;
   int p = 1;
   for (; p < 100; ++p) {
     sum_1 = sum_1 + p;
   }

   int sum_2 = 0;
   int q = 1;
   for (; q < n; ++q) {
     sum_2 = sum_2 + q;
   }
 
   int sum_3 = 0;
   int i = 1;
   int j = 1;
   for (; i <= n; ++i) {
     j = 1; 
     for (; j <= n; ++j) {
       sum_3 = sum_3 +  i * j;
     }
   }
 
   return sum_1 + sum_2 + sum_3;
 }

3), the multiplication rule, O (f (n)) * O (g (n)) = O (f (n) * g (n))

Scene: nested loop: T (n-) = O (F (n-) * G (n-))

T(n) = O(f(n) * g(n^2)) = O(f(n * n^2)) = O(f(n^3))

int cal(int n) {
   int ret = 0; 
   int i = 1;
   for (; i < n; ++i) {
     ret = ret + f(i);
   } 
 } 
 
 int f(int n) {
  int sum = 0;
  int i = 1;
  for (; i < n; ++i) {
    sum = sum + i;
  } 
  return sum;
 }

Three), common time complexity examples

(1) <O (logn) <(n) <(nlogn) <O (n ^ 2) <O (n ^ 3) <O (2 ^ n)

The (1):

As long as there loop, a recursive algorithm, even though there are thousands of lines of code, time complexity is O (1).

O (logn): geometric sequence.

2 ^ 0 2 ^ 1 2 ^ 3 ^ x = n ..... 2, x = logn

O (nlogn):

Loop nested loops with logn

D) when the two code complexity is determined by the size of data

O(m+m) = O(f(m)) + O(g(n))

O (m n) = O (f (m)) O (g (n))

Space complexity

Time complexity often encountered typically O (n) and O (n ^ 2)

Guess you like

Origin www.cnblogs.com/Auge/p/12051200.html
Recommended