Find the minimum k count and k count

Source: Internet
Author: User

Find the minimum k count and k count

Find the minimum k count


1. Description


Find the minimum k number in an array with a length of n. (The maximum k number solution is similar)


2. Sorting

The idea is relatively simple. First, sort the n number, and then enter the k Number.

The time complexity of this method is relatively large. Assume that we use the fast-forward mode and require O (nlogn). Then, we need O (k) to output k numbers, which requires O (nlogn )~


Code omitted.


3. The block movement method is relatively good, and the algorithm is simple and easy to implement. First, the first k number in the array is used as the minimum candidate block. Then, this block is moved back. Each time it is moved, the current number and the maximum number in the block are compared. If it is smaller than the maximum number, it is replaced, reselect the maximum number of blocks.
As shown in:


The time complexity of this method is O (k) + O (n-k) k = O (nk ).
Another way to improve is to put the k number in a maximum heap. Every time you move an update, it is a process of updating the heap, if the current number is smaller than the top element of the heap (the maximum number in k number), we will update the heap. The update heap only requires O (logk ). Therefore, the time complexity of this improvement method is O (nlogk ).
4. Quick Selection
This method is difficult to understand, but the time complexity is O (n ).
Reference: https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/02.01.md

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.