#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; }
点赞 评论

相关推荐

牛客网
牛客企业服务