I. Question
How to sort n numbers requires time complexity O (N) and space complexity O (1)
Ii. Answers
Key: hash table, meaning of 1 in space complexity O (1) (as long as it is a constant)
It seems that any knownAlgorithmIf anyone does, all sorting methods: quicksort, shellsort, heapsort, bubblesort, and so on can be discarded. What should these algorithms do? But in fact, when there is a limit on the number range, there is an algorithm like this. You only need to use an array to record the number of occurrences of each number.
Assume that your number ranges from 0 to 65535 and defines an array count [65536] (This space is a constant and has nothing to do with N, so it is O (1 )), the initial values are all 0.
Suppose there are the following numbers:
100,200,300,119, 0, 6...
For each number, record it in count:
100 => count [100] ++
200 => count [200] ++
300 => count [300] ++
119 => count [119] ++
0 => count [0] ++
6 => count [6] ++
...
Finally, you can get 0 to all the numbers on the traversal side ~ 65535 the number of each number (in the count array), and then traverse the Count array sequentially. Count [N] = m, then output M n, (for example, if Count [3] = 2, there are two numbers 3), output them in sequence, and finally obtain the result. The first traversal is O (n), the second traversal is O (1), is a constant, so the last time complexity is O (n), and the space complexity is O (1)
This algorithm is very simple. I believe everyone will, but this question is too abnormal and will usually scare the interviewer.