[大根堆]面試題40. 最小的k個數(easy)

題目:
在這裏插入圖片描述
題解:

  • 大根堆模板題,維持一個大小爲 k 的大根堆就可得到數組前 k 個最小數了。

代碼如下:

class Solution {
public:
    vector<int> getLeastNumbers(vector<int>& arr, int k) {
        if(!k)return {};
        priority_queue<int> heap;//維持大小爲k的大根堆
        for(int a:arr){
            if(heap.size()<k)heap.push(a);
            else{
                if(heap.top()<=a)continue;//元素比堆頂元素值大,不需要添加到堆中
                else{
                    heap.pop();
                    heap.push(a);
                }
            }
        }
        vector<int> res;
        while(!heap.empty()){
            res.push_back(heap.top());
            heap.pop();
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章