Find the smallest number of K
1. Title Description
In an array of length n, look for the smallest number of K. (the largest K-number solution is similar)
2. Sorting Method
The idea is relatively simple, first to the n number of orders, and then enter the number of k above, you can.
This method has a large time complexity. Suppose we use the fast row, need O (Nlogn), and then output the K number need O (k), altogether to O (NLOGN) ~
Code slightly.
3. Block Move MethodThis method is better, the algorithm is simple and easy to implement. first the number of the first k in the array as the minimum candidate, and then move the block back, each time you move the current number and the maximum number of blocks, if it is smaller than the maximum number, replace, re-select the maximum number in a block.
as shown in the following:
The time complexity of this method is O (k) +o (n-k) K=o (NK).
another way to improve this is to put the K number in a maximum heap , and then each time the update is moved, it is a process of updating the heap, if the current number is smaller than the top element of the heap (the maximum number of k), then we update the heap. The update heap requires only O (LOGK). So the time complexity of this improved method is O (NLOGK).
4. Quick Selection Method
This method is more difficult to understand, but the time complexity is O (n).
Reference Links:https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/02.01.md
Find the smallest number of K