[Programmer interview questions: 100] 5. Find the minimum k elements, Programmer

Source: Internet
Author: User

[Programmer interview questions: 100] 5. Find the minimum k elements, Programmer
[Question]

Enter n integers and the minimum k integers.

For example, if you enter the 8 numbers 1, 2, 3, 5, 6, 7, and 8, the minimum four digits are 1, 2, 3, and 4.

[Analysis]

The simplest way to solve this problem is to sort the input n integers so that the number of k at the top is the minimum number of k. The time complexity of this approach is O (nlogn ). We try to find a faster solution.

We can first create a data container with the size of k to store the minimum k numbers. Next we will read a number from the input n integers each time. If the number in the container is less than k, put the integer read this time into the container. If there are k numbers in the container, that is, the container is full, at this time, we cannot insert a new number but can only replace an existing number. We can find the maximum value of the existing k number, and compare it with the integer to be inserted this time. If the value to be inserted is smaller than the current maximum value, replace the current maximum value with this number. If the value with insert is larger than the current maximum value, therefore, this number cannot be one of the smallest k integers, because we already have k numbers in our container smaller than it, so we can discard this integer.

Therefore, when the container is full, we need to do three things: one is to find the maximum number in k integers, and the other is to delete the maximum number in the container, 3. Insert a new number and ensure that k integers are still sorted. If we use a binary tree to implement this data container, we can implement these three steps in the O (logk) time. Therefore, for n input numbers, the total time efficiency is O (nlogk ).

We can use different binary trees to implement this data container. Since we need to find the largest number in k integers every time, we can easily think of using the largest heap. In the max heap, the value of the root node is always greater than the value of any node in its subtree. Therefore, we can obtain the maximum value of the existing k numbers in O (1), but it takes O (logk) Time to delete and insert.

We can implement a maximum heap by ourselves.

We can also use the red and black trees to implement our containers. The red-black tree divides the nodes into red and black colors and ensures that the tree is balanced according to some rules, in this way, O (logk) is only required for searching, deleting, and inserting data in the red/black tree ). In STL, set and multiset are both implemented based on the red and black trees. If the interviewer is not opposed to using the data container in STL.

[Code]

/********************************** Date: * Author: SJF0115 * Subject: 5. find the smallest k elements * Source: * category: select **********************************/ # include <iostream> using namespace std; // adjust the subtree with index as the root // n: number of elements in the heap void MaxHeap (int a [], int index, int n) {if (n <2) {return;} int largestIndex = index; // The subscript of the Left subnode int leftIndex = 2 * index; // The subscript of the right subnode int rightIndex = 2 * index + 1; // maximum left subnode if (leftIndex <= n & a [left Index]> a [largestIndex]) {largestIndex = leftIndex ;} // if // maximum if (rightIndex <= n & a [rightIndex]> a [largestIndex]) {largestIndex = rightIndex ;} // if a [index] is the largest, the subtree rooted in index is already the largest heap. Otherwise, the subnode of index has the largest element. // The value is exchanged for a [index], a [LargetIndex], so that the index and children can satisfy the heap int temp; if (largestIndex! = Index) {// exchange temp = a [largestIndex]; a [largestIndex] = a [index]; a [index] = temp; // re-adjust the subtree MaxHeap (a, LargestIndex, n) with largestIndex as the root;} // if} // create a heap: convert an array a [1-n] into a maximum heap void BuildMaxHeap (int a [], int n) {// sub-array a [(n/2 + 1, n/2 + 2 ...... n)] all elements in the tree do not need to be adjusted for (int I = n/2; I> = 1; I --) {// adjust the tree with I as the root node to make it the largest heap MaxHeap (a, I, n) ;}// Heid HeapSort (int * & a, int n) {int tmp; // if the maximum element in the array is in root a [1], you can use it to exchange with a [I] to obtain the final correct position for (int I = n; i> 1; I --) {// exchange tmp = a [I]; a [I] = a [1]; a [1] = tmp; // a [I] has reached the correct position. Remove n -- From the heap; // re-adjust MaxHeap (a, 1, n );}} // minimum K Number void MinK (int a [], int k, int n) {for (int I = k + 1; I <= n; I ++) {// If X is larger than Y, the original heap does not need to be changed. // If X is smaller than Y, replace Y with Y, // after replacement, X may damage the structure of the Max heap. You need to adjust the heap to maintain the int temp; if (a [I] <a [1]) {temp = a [I]; a [I] = a [1]; a [1] = temp; // re-adjust the MaxHeap (a, 1, k) ;}// HeapSort (a, k); // output for (int I = 1; I <= k; I ++) {cout <a [I] <endl ;}} int main () {int k = 5; // a [0] No, the root node of the heap is int a [] = {0, 3, 17,8, 27,7, 20,5, 35,6} starting from 1; // bucket maxheap constructs a maximum heap BuildMaxHeap (, k); // minimum k elements MinK (a, k, 9); return 0 ;}






Reference: heap sorting

Find the maximum number of K in the beauty of Programming







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.