题目描述
1 class Solution { 2 public: 3 vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { 4 vector<int> res; 5 int len = input.size(); 6 if (k <= 0 || k > len) //k不符合条件的话,均返回空 7 return res; 8 priority_queue<int,vector<int> > pq; 9 for (int i = 0; i < len; i++) { 10 if (pq.size() < k) { 11 pq.push(input[i]); 12 } else { 13 int temp = pq.top(); 14 if (input[i] < temp) { 15 pq.pop(); 16 pq.push(input[i]); 17 } 18 } 19 } 20 while (!pq.empty()) { 21 int top = pq.top(); 22 pq.pop(); 23 res.push_back(top); 24 } 25 //sort(res.begin(), res.end()); 26 return res; 27 } 28 };