JZ29 最小的K个数

本文最后更新于:2022年4月9日 中午

image-20211008104038953

Solution

  • 优先队列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> res;
if (input.size() == 0 || k <= 0 || k > input.size())
return res;
priority_queue<int> pq;
for (int num : input) {
if (pq.size() >= k) {
pq.push(num);
pq.pop();
} else
pq.push(num);
}
while (!pq.empty()) {
res.push_back(pq.top());
pq.pop();
}
return res;
}
};