Time complexity is the cornerstone of learning algorithms, so today we’re going to talk about why time complexity is introduced, what time complexity is and how to calculate the time complexity of an algorithm
First, describe the running time of the algorithm
Some day, huineng called a dust plan to give him to cram cram basic knowledge, I saw ke wrote a very simple code
A dust to see the teacher a little angry, began to consult humbly
For the sake of discussion, let’s treat the execution time of each statement as the same, denoted as a unit of time
① The two statements in the blue box take two units of time
② A statement in the black box takes n+1 time units
(3) The two statements in the red box take 2*n time units
Isn’t this mathematics, yichen thought to himself
Where n is what we call the size of the problem, it’s the size of the problem you’re dealing with
Huineng just drew a diagram of this function
This article focuses on the relationship between problem size and running time, assuming that different inputs are basically independent of running time
Second, time complexity
For example, if T(n)=3n+3, the constant 3 and the coefficient 3 on n have very little effect on the result of the function when n is very large
Such as:
T(n)=n+1 ignore the constant terms T(n)~n
T(n)=n+n^2 ignore the lower order terms T(n)~n^2
T(n)=3n ignores the highest order coefficients T(n)~n
Fortunately do not have to master that headache of mathematics, a dust thought in the heart
One dust pulled the topic back again
More precisely, O represents an asymptotically upper bound on the running time function, that T(n) is on the order of magnitude less than or equal to f(n).
Three, time complexity calculation
First, get the running time function. Second, simplify the function
① Replace all the addition constants in the running time with the constant 1
② In the modified function, only the highest order term is retained. ③ If the highest order term exists and is not 1, the coefficient of this term is ignored
O(1) is also called the constant order
Yi Chen conveniently wrote a nested loop code
Then, Huineng wrote the logarithmic code for a period of time
Always mathematics is not very good one dust at this time a little meng
In addition, about the data structure and algorithm learning, you can see this PDF, the various algorithm template are summarized, follow to learn:
Two months to get 70K star, the first byte of great god brush notes
The issue of
2. Stop asking me what a skip list is
3. Stop asking me what is a binary heap
4. Stop asking me what’s wrong with AVL tree
5. Stop asking me what is a red-black tree
6. Stop asking me what a trie tree is
7. Hash Design Principles (1)
8. Hash Design Principles (Middle)
9. Hash Design Principle: Open Address Method (part 2)