k-选取问题
#include <iostream> #include <vector> #include<cassert> #include <queue> using namespace std; auto func(vector<int> nums, size_t k) { assert(!nums.empty() || k <=nums.size()); priority_queue<int> heap; for (size_t i = 0; i < nums.size(); i++) { if (heap.size() < k) heap.push(nums[i]); else { if (nums[i] < heap.top()) { heap.pop(); heap.push(nums[i]); } } } return heap; } int main() { vector<int> nums{ 5, 1, 3, 4, 9, 8, 8, 2 }; auto fc = func(nums, nums.size() / 2); while (!fc.empty()) { cout << fc.top(); fc.pop(); } }
所望隔山海