What is time complexity and space complexity

       In fact, time complexity and space complexity are the criteria for measuring the quality of an algorithm. For example, when we buy apples, we must most want to buy the cheapest and sweetest apples. If apples are sweet or not, one bite will give you the taste. Our most intuitive feeling is to compare the two apples which is sweeter. The time complexity and space complexity are for this. The names are different and the purpose is the same. It is to judge the quality of the algorithm.

Insert picture description here

       Let’s talk about an algorithm. Everyone must have heard the story of Gauss’s childhood. When Gauss was in the fourth and fifth grades, Gauss’ math teacher asked Gauss to add a problem from 1 to 100. Gauss’s teacher thought He would honestly count and add one by one. Unexpectedly, Gaussian thinking was quick and he used the arithmetic sequence method. First, the addition of 1 and 100 equals 101, and the addition of 2 and 99 equals 101, 100 numbers. There are 50 groups of 101, 50 times 101 equals 5050, Gaussian quickly calculated it, it is really smart. Among them, the algorithm is designed. It can be calculated by adding one by one, but the speed is very slow, and the arithmetic sequence can be calculated quickly and efficiently. It is the same principle. Everyone definitely likes to eat sweet apples. Good algorithm.

Insert picture description here

       So when we write code, the goal is to write code that runs fast and takes up less space. Such code is ideal code. T(n) is a sign of the time complexity of recording. Generally, the time complexity of code is four common types:

T (n) = O (1)
T (n) = O (logn)
T (n) = O (n)
T (n) = O (n ^ 2)

The relationship between them is like this:

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

In addition, there is a lot of time complexity

T (n) = O (nlogn)
T (n) = O (n ^ 3)
T (n) = O (mn)
T (n) = O (2 ^ n)

       The time complexity is mainly for a large amount of data, because the quality of the two algorithms can only be reflected in the case of a large amount of data, so I run with you and a fat man. At first, there is no obvious difference between the two of you, but after a long time, The fat man started to pant.
       The main expression method of space complexity: S(n)=O(f(n)), where n is the size of the problem, and f(n) is a function of the storage space occupied by the algorithm. The algorithm takes the same time. Of course, the smaller the space, the better. The order of common space complexity from low to high is as follows

O(1), O(n), O(n^2), the greater the recursion depth, the larger the space occupied

        Welcome everyone to pay attention to my WeChat public account: Ning Tsai talks about python, and strive to share more easy-to-understand and interesting python knowledge for you! Make learning fun and easy!

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43697214/article/details/108319738