Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Preface:

May be bad at math, for all kinds of operation how many have conflict, but is ultimately escapes, want to write a concise, easy to maintain code, algorithm is escapes, it feels like, oneself have no matter to create martial arts and suddenly one day to the secret but need a lot of time to practice qigong contrast, only crustily skin of head, for the win ~! Dubious!

1. Big O notation:

From the Diagrams of algorithms, the big O notation is a special notation that indicates how fast the algorithm is. The ability to compare operands indicates the growth of the algorithm’s running time.

  • The running time of the algorithm is not measured in seconds.
  • The running time of the algorithm is fromgrowthIs measured by the Angle of.
  • The running time of the algorithm is expressed in big O notation.

2.Time complexity:

Time complexity is used to qualitatively describe the running time of the algorithm. (As mentioned above, not in seconds, but in general)

Here are some common graphs of time complexity:

2.1 Time complexity O(1):

let a = 996;
a +=1;
Copy the code
  • The above two lines of code are executed only once each time the code is executed, so the time is O(1).

2.2 Time complexity O(n):

for(let i=0; i < n; i++){console.log(n)
}
Copy the code
  • The code above is a simple loop,The for loopThe code is executed innThe secondary time complexity isO(n);

2.3 Time complexity O(n^2)

for(let i=0; i < n; i++){for(let j=0; j < n; j++){console.log(i,j); }}Copy the code
  • A two-layer for loop is a loop within a loop

2.4 Time complexity O(logN):

What does logN mean?

That’s the same thing as asking 2 to what power is N?

let i = 1;
while(i < N){
	console.log(i);
	i *= 2;
}
Copy the code
  • The above code iswhileA loop is just a number multiplied over and over again2Until this is greater thanNThe loop stops and the code executeslogNtime

3. Spatial complexity:

Like time complexity, spatial complexity is expressed in big O notation.

Space complexity: A measure of the amount of storage space temporarily occupied by an algorithm while it is running.

3.1 Space complexity O(1):

The examples are omitted as above

3.2 Space complexity O(n):

let arr = [];
for(let i = 0; i < 0; i+=1){
	arr.push(i);
}
Copy the code
  • Take upnSo the space complexity of this code is zeroO(n);

3.3 Space complexity O(n^2):

let square=[];
for(let i=0; i < n; i++){ square.push([]);for(let j=0; j < n; j++){ square[i].push(j) } }Copy the code
  • A two-digit array is just a matrix.