Find the smallest number of K

Source: Internet
Author: User

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

Related Article

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.