content
1. What is time complexity and space complexity
2. How to calculate time complexity and space complexity
2.2 Calculate the time complexity of some commonly used algorithms
2.3 Calculate the space complexity of some commonly used algorithms
3. Algorithm practice questions that require complexity
1. What is time complexity and space complexity
Before understanding the two complexities, let's first understand what the efficiency of an algorithm is.
The efficiency of the algorithm is divided into two types: time efficiency and space efficiency
1. Time efficiency is called time complexity, which mainly measures the running speed of an algorithm
2. Space efficiency is called space complexity, which is mainly a measure of the additional space required by an algorithm
1.1 Time complexity
The time spent by an algorithm is proportional to the number of executions of the statements in it, and the number of executions of the basic operations in the algorithm is the time complexity of the algorithm.
1.2 Space complexity
Space complexity is a measure of how much storage space is temporarily occupied during the operation of an algorithm . The space complexity is not how many bytes of space the program occupies, so the space complexity is the number of variables.
2. How to calculate time complexity and space complexity
2.1 Using the Big O method
When calculating the space complexity in practice, it is not necessary to calculate the exact number of executions, but only the approximate number of executions, so we use the asymptotic representation of big O.
Derive the big-O method:
1. Replace all additive constants in runtime with the constant 1. [O(100)=>O(1)]
2. In the modified run times function, only the highest order term is kept. [O(n*n+2n+10)=>O(n^2)] [O(n+10)=>O(n) ]
3. If the highest-order term exists and is not 1, remove the constant multiplied by this term. The result is a big-O order.
2.2 Calculate the time complexity of some commonly used algorithms
Calculate the time complexity of Funcl
Calculate the time complexity of strchar
2.3 Calculate the space complexity of some commonly used algorithms
The space complexity is a measure of the size of the storage space temporarily occupied by an algorithm during the running process, and the number of variables is calculated.
Time is cumulative, space is not cumulative
The cycle has gone a few times, and the reuse is a space
Calculate the space complexity of bubble sort
Calculate the space complexity of Factorial
3. Algorithm practice questions that require complexity
Interview Question 17.04. Disappearing Numbers - LeetCode (leetcode-cn.com)
189. Rotation Array - LeetCode (leetcode-cn.com)