题目:
解答:
C++实现起来用priority_queue容器,默认从小到大排序,底层实现为最大堆。
1 class Solution { 2 public: 3 vector<int> smallestK(vector<int>& arr, int k) 4 { 5 vector<int> res; 6 priority_queue<int> q; 7 for (int a : arr) 8 { 9 q.push(a); 10 if (q.size() > k) 11 { 12 q.pop(); 13 } 14 } 15 while (!q.empty()) 16 { 17 res.push_back(q.top()); 18 q.pop(); 19 } 20 return res; 21 } 22 };