剑指OFFER----面试题40. 最小的k个数

链接:https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/submissions/

 

代码:

class Solution {
public:
    vector<int> getLeastNumbers(vector<int>& arr, int k) {
        vector<int> res;
        priority_queue<int> h;
        for (auto x: arr) {
            h.push(x);
            if (h.size() > k) h.pop();
        }
        while (h.size()) res.push_back(h.top()), h.pop();
        reverse(res.begin(), res.end());
        return res;
    }
};

 

posted @ 2020-03-03 20:56  景云ⁿ  阅读(78)  评论(0编辑  收藏  举报