剑指 Offer 40. 最小的k个数(堆实现)

91 阅读1分钟

c++堆类模板代码

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
using namespace std;
template<typename T>
class Heap :public vector<T>
{
public:
    template<typename Func_T>
    Heap(Func_T cmp):cmp(cmp){}
    void push(const T &a){
       this-> push_back(a);
        push_heap(this->begin(),this->end(),cmp);
        return;
    }
    void pop(){
            pop_heap(this->begin(),this->end(),cmp);
            this->pop_back();
            return;
    }
    T&top() {return this->at(0);}
    private:
    std::function<bool(T,T)> cmp;
};

输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。

示例 1:

输入:arr = [3,2,1], k = 2
输出:[1,2] 或者 [2,1]
示例 2:

输入:arr = [0,1,2,1], k = 1
输出:[0]


来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/zu…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

实现

/*用大顶堆来维护最值集合,将arr的值不断压入大顶堆h中,当h.size>k时,再将堆顶元素pop*/
#include<iostream>
#include<vector>
#include<algorithm>
#include<set>
#include<map>
#include<stack>
#include<functional>
using namespace std;
template<typename T>
class Heap :public vector<T>
{
public:
    template<typename Func_T>
    Heap(Func_T cmp):cmp(cmp){}
    void push(const T &a){
       this-> push_back(a);
        push_heap(this->begin(),this->end(),cmp);
        return;
    }
    void pop(){
            pop_heap(this->begin(),this->end(),cmp);
            this->pop_back();
            return;
    }
    T&top() {return this->at(0);}
    private:
    std::function<bool(T,T)> cmp;
};
class Solution {
public:
    vector<int> getLeastNumbers(vector<int>& arr, int k) {
Heap<int>h{less<int>()};
for(auto x:arr)
{
    h.push(x);
    if(h.size()>k) h.pop();
}
return h;
    }
};