A seemingly scary algorithm interview question: how to sort n numbers requires time complexity O (N) and space complexity O (1)
Source: Internet
Author: User
It seems that no known algorithm can be implemented. If anyone does, all the sorting methods, such as quicksort, shellsort, heapsort, and bubblesort, can be discarded, what are these algorithms. 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: 10020030011906... 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. It's just that this question is too abnormal and will usually scare the interviewer (I used to have this question during the interview, however, the expression of the question should be "friendly", haha)
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.