Algorithm Time Complexity Calculation

Table of contents

1. Time complexity calculation

1.1 Time Complexity Examples

1.1.1 Examples

1.1.2 Examples

1.1.3 Examples

1.1.4 Examples

1.2 Time complexity leetcode example


1. Time complexity calculation

       First of all, we need to understand what time complexity is: the time complexity of an algorithm refers to the time resources that the algorithm needs to consume when it is running after it is written into an executable program—in layman’s terms, it is the speed at which an algorithm runs. (Number of basic operations in the algorithm)


Because it is too troublesome to calculate the specific number of executions, it is introduced - the progressive expression of big O (estimation)


1.1 Time Complexity Examples

Calculating Time Complexity Using Big O's Asymptotic Expression

1.1.1 Examples

Answer: F(N)=2*N+10

          Since the constant has little effect on the result, it is directly expressed by the big O asymptotic expression: the time complexity is O(N)


1.1.2 Examples

 Analysis: Since the cycle is 100 times, it is a constant time, and the time complexity of the constant cycle is O(1)


1.1.3 Examples

 

 Observe the character lookup function above: we can see that there are three cases of time complexity at this time —>

1. Best case: run it once and find out

2. Neither good nor bad: N/2 times to find

3. Worst case: N times found

But the time complexity is the worst case: the above time complexity is O(N)


1.1.4 Examples

 Calculate the time complexity of the binary search above:

Analysis: We can understand binary search as a long piece of paper that is constantly folded in half

1. The number of 2s will be divided by how many times it is folded in half.

   In addition to how many 2s, how many times have you searched

2. Assume that x times are searched, so there is the following calculation

Note: We can't count cycles, this is not necessarily accurate, we must use algorithmic thinking to calculate

1.2 Time complexity leetcode example


 Here we can use the XOR method:
1. The characteristics of XOR, the same XOR result is 0, and the different XOR result is 1.

2. You can use the same two numbers to XOR and the result is 0 to find the missing number

Answer: Assume that the array is 0 to 6, 7 numbers, and the 5 numbers of 012345 are passed in, then set x=0, XOR with the array that lacks numbers, and then XOR with the complete array, and the result is obtained It's the missing number.

Code:

Guess you like

Origin blog.csdn.net/qq_58286439/article/details/130066119