
堆排序
点击查看代码
class Solution {
public:
vector<int> getLeastNumbers_Solution(vector<int> input, int k) {
priority_queue<int> heap;
for (auto x : input) {
heap.push(x);
if (heap.size() > k) heap.pop();
}
vector<int> res;
while (heap.size()) res.push_back(heap.top()), heap.pop();
reverse(res.begin(), res.end());
return res;
}
};
- 维护一个大根堆 heap,每次把 vector 中的元素放入到 heap 中,当 heap 中元素的个数大于 k 时,使用 heap.pop() 移除 heap 中的最大值;
快速选择
点击查看代码
class Solution {
public:
vector<int> getLeastNumbers_Solution(vector<int> input, int k) {
vector<int> res;
for (int i = 1; i <= k; i ++) {
res.push_back(quick_select(input, 0, input.size() - 1, i));
}
return res;
}
int quick_select(vector<int> q, int l, int r, int k)
{
if (l >= r) return q[l];
int i = l - 1, j = r + 1, x = q[l + r >> 1];
while (i < j) {
do i ++; while (q[i] < x);
do j --; while (q[j] > x);
if (i < j) swap(q[i], q[j]);
}
if (k <= j - l + 1) return quick_select(q, l, j, k);
else return quick_select(q, j + 1, r, k - (j - l + 1));
}
};
- quick_select 模板;