关注
#include <iostream>
(30316)#include <queue>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findKSmallest(vector<int>& nums, int k) {
// 定义一个大顶堆(使用priority_queue,默认是大顶堆)
priority_queue<int> max_heap;
for (int num : nums) {
if (max_heap.size() < k) {
max_heap.push(num);
}
else if (num < max_heap.top()) {
max_heap.pop();
max_heap.push(num);
}
}
vector<int> result;
while (!max_heap.empty()) {
result.push_back(max_heap.top());
max_heap.pop();
}
return result;
}
};
int main() {
vector<int> nums = {4, 2, 7, 1, 9, 3, 5};
int k = 3;
Solution solution;
vector<int> result = solution.findKSmallest(nums, k);
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}
查看原帖
点赞 评论
相关推荐
昨天 10:37
安徽大学 全栈开发 点赞 评论 收藏
分享
牛客热帖
正在热议
# 25届秋招公司红黑榜 #
27495次浏览 213人参与
# 一人分享一句让你在秋招振作起来的话 #
12593次浏览 279人参与
# 字节求职进展汇总 #
280792次浏览 3223人参与
# 校招入职后的感受 #
128603次浏览 1732人参与
# 海康威视求职进展汇总 #
300217次浏览 2852人参与
# 你的简历改到第几版了 #
651175次浏览 9535人参与
# 你最希望上岸的公司是? #
16990次浏览 185人参与
# 最后再改一次简历 #
1722529次浏览 27427人参与
# 找实习多的是你不知道的事 #
1243820次浏览 17639人参与
# 华子oc时间线 #
18199次浏览 81人参与
# 美的求职进展汇总 #
192394次浏览 1577人参与
# 如果校招重来我最想改变的是 #
169426次浏览 2307人参与
# 校招我听劝 #
85371次浏览 1086人参与
# 我想象的实习vs现实的实习 #
216360次浏览 1923人参与
# 如何写一份好简历 #
558140次浏览 8098人参与
# 写简历别走弯路 #
586571次浏览 7269人参与
# 秋招想进国企该如何准备 #
10164次浏览 132人参与
# 双非有机会进大厂吗 #
31173次浏览 291人参与
# 招银网络求职进展汇总 #
71419次浏览 511人参与
# 你已经投递多少份简历了 #
577473次浏览 7106人参与