Original blog, reproduced please indicate the source!
GitHub Address
# topics
Enter n integers to find the smallest number of K. For example, enter 4,5,1,6,2,7,3,8 these 8 numbers, then the smallest 4 numbers are 1,2,3,4
# ideas
1. The idea based on partition
Time Complexity of O (n)
2. Thinking based on red and black trees
First, a container of size k is used to store the smallest number of k digits, and then each time a number is entered from the input n integers, if the number already in the container is less than K, the integer read is placed directly into the container, and if there are already k numbers in the container, no new numbers can be inserted and only the existing ones are replaced. Principle of substitution: if the value to be inserted is m smaller than the maximum value n in the container, M replaces N, and if the value to be inserted is m greater than the maximum value n in the container, it remains unchanged. (Find maximum values in k integers, delete container maximums, insert a new number)
Complexity of Time: O (N*LOGK)
# code
1. The idea based on partition
2. Thinking based on red and black trees
1 //using red and black trees to achieve2 classSolution {3 Public:4vector<int> Getleastnumbers_solution (vector<int> Input,intK) {5 //Special input6 if(Input.size () <=0| | K>input.size ())returnvector<int> ();7 8 //An iterator that creates the largest element of a multiset and multiple sets of results9multiset<int, greater<int> > Res;Tenmultiset<int, greater<int> >::iterator res_best; One A //Traversal input -vector<int>::iterator input_ite = Input.begin ();//Vector iterators - for(; Input_ite!=input.end (); input_ite++) the{ - //Insert the first k elements into the collection - if(Res.size () <k) -Res.insert (*input_ite); + Else -{ + iterator to the largest element in the//multi-collection ARes_best = Res.begin (); at //Compare + DELETE + Insert - if(*input_ite<* (Res.begin ())) -{ -Res.erase (res_best); -Res.insert (*input_ite); -} in} -} to returnvector<int> (Res.begin (), Res.end ()); +} -};
The smallest number of K, C + + implementation