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();
    }
}

 

posted @ 2020-10-15 15:16  世界を変える御宅族  阅读(156)  评论(0编辑  收藏  举报