题解 | #小根堆直接输出——最小的K个数#

最小的K个数

https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf

/*
将所有元素输入小根堆,输出小根堆的前k个结点即为答案
*/
#include <vector>
class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        vector<int> res;
        priority_queue<int, vector<int>, greater<int>> q;
        if(k==0 || input.size() == 0) return res;
        for(int i=0;i<input.size();i++) q.push(input[i]);
        for(int j=0;j<k;j++){
            res.push_back(q.top());
            q.pop();
        }
        return res;
    }
};

全部评论

相关推荐

09-22 15:45
门头沟学院 Java
谁给娃offer我给...:我也遇到了,我说只要我通过面试我就去,实际上我根本就不会去😁
点赞 评论 收藏
分享
牛客83265014...:完了,连现在都没开始面,13号投的是不是晚了
秋招的第一个offer,...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务