面试题40. 最小的k个数

题目:

 

 

解答:

 1 class Solution {
 2 public:
 3     vector<int> getLeastNumbers(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     }
23 };

 

posted @ 2020-05-09 16:26  梦醒潇湘  阅读(152)  评论(0)    收藏  举报