class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> res;
        if(k > input.size()) return res;
        
        priority_queue<int> heap;
        for(auto x : input)
        {
            heap.push(x);
            if(heap.size() > k) heap.pop(); //如果当前大根堆中的元素>k个
        }
        while(heap.size())
        {
            res.push_back(heap.top());
            heap.pop();
        }
        //大根堆 - > 按照从到大数序排列所以要逆序
        reverse(res.begin(),res.end());
        return res;
    }
};
2020-05-16
在牛客打卡24天,今天学习:刷题 6 道/代码提交 6 次
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务