53. 最小的k个数

题目地址:https://www.acwing.com/problem/content/description/49/

AC代码 make_heap

class Solution {
public:
    vector getLeastNumbers_Solution(vector input, int k) {
        auto cmp = [](int a,int b){ return a>b; }; //类或者匿名函数
        make_heap(input.begin(),input.end(),cmp);
        vector res;
        while(k--){
            res.push_back(input.front());
            pop_heap(input.begin(),input.end(),cmp);
            input.pop_back();
        }
        return res;
    }
};

AC代码 priority_queue

class Solution {
public:
    vector getLeastNumbers_Solution(vector input, int k) {
        priority_queue,greater> q;
        vector res;
        for(auto e:input) q.push(e);
        while(k--){
            res.push_back(q.top());
            q.pop();
        }
        return res;
    }
};

AC代码 手动建堆

class Solution {
public:
    void adjust_heap(vector& v,int len,int i){
        int lc=2*i+1,rc=2*i+2,tar=i;
        while(lc& v){
        for(int i=v.size()/2-1;i>=0;i--)
            adjust_heap(v,v.size(),i);
    }

    vector getLeastNumbers_Solution(vector input, int k) {
        make_heap(input);
        vector res;
        while(k--){
            res.push_back(input[0]);
            swap(input[0],input.back());
            input.pop_back();
            make_heap(input);
        }
        return res;
    }
};

总结

复习堆

你可能感兴趣的:(53. 最小的k个数)