[100 questions] sorting of 49th questions requires time complexity O (N) and space complexity O (1)

Source: Internet
Author: User

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.

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.