题解 | #最小的K个数#

最小的K个数

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

#include <queue>
class Solution {
public:
    vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
        /*
        vector<int> ret;
        if(k==0||k>input.size()){
            return ret;
        }

        sort(input.begin(),input.end());
        ret.assign(input.begin(), input.begin()+k);
        return ret;

        */
        vector<int> ret;
        if(k==0||k>input.size()){
            return ret;
        }

        priority_queue<int,vector<int>> heapK;
        //iterate the array,if the number of elements in the array is smaller than k,push
        //greater,compare the largest number in k with the current element,choose the smaller
        

        for(const int CurVal:input){
            if(heapK.size()<k){
                heapK.push(CurVal);
            }
            else if(CurVal<heapK.top()){
                heapK.pop();
                heapK.push(CurVal);
            }
        }
        while(!heapK.empty()){
            ret.push_back(heapK.top());
            heapK.pop();
        }

        return ret;


    }
};

·大小为k的堆插入复杂度为 log2 k

·

全部评论

相关推荐

_mos_:要不是看评论区我都不知道你要找的是数分
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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