Question: Enter n Integers to find the minimum K number. For example, if you enter the 8 digits {,}, the minimum 4 digits are 1, 2, 3, 4.Analysis
This question is followed by another question: interview question 29: The number that appears more than half of the number in the array is similar, all of which are solved through the concept of partition. Obtain the index through partition () and determine that the index is = K. If the value is K, the number of K on the left of the index is smaller than the number pointed by the index, it is also smaller than the number on the right of the index. Then we can find the minimum K number required by this question. If the index is greater than K, the number smaller than K is between [start, index-1]. If the index is <K, the number smaller than K is in [index + 1, end. Knowing that the final obtained Index = K, exit the loop. Then output the number between [0, k), that is, the minimum K number.
Code instance view code
# Include <iostream> # include <stdlib. h> using namespace STD; int partition (INT arry [], int start, int end) {int partition tkey = arry [start]; while (start <End) {While (start <End & arry [end]> = begin tkey) end --; arry [start] = arry [end]; while (start <End & arry [start] <= pivotkey) Start ++; arry [end] = arry [start] ;}arry [start] = pivotkey; return start;} int getleastnumbers (INT arry [], int K, int Len) {If (arry = NULL | K <= 0 | K> Len | le N <= 0) {cout <"input error" <Endl; Return-1;} int start = 0, end = len-1; int Index = partition (Arry, start, end); While (K! = Index) {If (index> K) Index = partition (Arry, start, index-1); else Index = partition (Arry, index + 1, end );} return K;} void main () {int arry [] = {, 3}; // defines the array int Len = sizeof (arry)/sizeof (INT ); // evaluate the array length int K = 3; int Index = getleastnumbers (Arry, K, Len); For (INT I = 0; I <index; I ++) cout <arry [I] <"; cout <Endl; System (" pause ");}Processing Methods for Massive Data Processing
If the amount of data to be processed is very large, sorting is impractical. We can calculate the minimum K number through a data structure such as a large root heap.
Create a K-sized big root heap and traverse the data file. If the big root heap is not satisfied, insert the number to the big root heap. If the big root is full, compare the number of heap peaks with the number of reads. If the number is smaller than the number of heap peaks, delete the number of heap roofs and insert the number of just scans. Scan all data in this way. The time complexity is O (nlog (k ))