题目:输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
1 vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { 2 vector<int> result; 3 if(input.size()<=0||input.size()<k) 4 return vector<int>(); 5 6 multiset<int,greater<int>> leastNumber; 7 vector<int>::iterator inputIter = input.begin(); 8 for(;inputIter!=input.end();inputIter++){ 9 if(leastNumber.size()<k) 10 leastNumber.insert(*inputIter); 11 else{ 12 multiset<int,greater<int>>::iterator leastIter = leastNumber.begin(); 13 if(*inputIter < *leastIter){ 14 leastNumber.erase(leastIter); 15 leastNumber.insert(*inputIter); 16 } 17 } 18 } 19 return vector<int>(leastNumber.begin(),leastNumber.end()); 20 }