题解 | #最小的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

·

全部评论

相关推荐

秋盈丶:后续:我在宿舍群里和大学同学分享了这事儿,我好兄弟气不过把他挂到某脉上了,10w+阅读量几百条评论,直接干成精品贴子,爽
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务