面试题30 最小的K个数
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
1 class Solution { 2 public: 3 multiset<int, greater<int>> a; 4 vector<int> v; 5 vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { 6 a.clear(); 7 if (k < 1 || input.size() <= 0 || k > input.size()){ 8 return v; 9 } 10 11 for (int i = 0; i < input.size(); i++){ 12 if (a.size() < k) 13 a.insert(input[i]); 14 else{ 15 multiset<int, greater<int>>::iterator iter = a.begin(); 16 if (*iter > input[i]){ 17 a.erase(iter); 18 a.insert(input[i]); 19 } 20 } 21 } 22 multiset<int, greater<int>>::iterator iter = a.begin(); 23 while (iter != a.end()){ 24 v.push_back(*iter); 25 iter++; 26 } 27 return v; 28 } 29 };