最小的k个数

输入n个整数,找出其中最小的k个数。

注意:

  • 数据保证k一定小于等于输入数组的长度;
  • 输出数组内元素请按从小到大顺序排序;

样例

输入:[1,2,3,4,5,6,7,8] , k=4

输出:[1,2,3,4]

算法:堆(priority_queue)。我们维护一个堆,每次不断将数组中的元素加入进来(当且仅当堆顶元素大于此时数组的元素时)。
class Solution {
public:
    vector<int> getLeastNumbers_Solution(vector<int> input, int k) {
        priority_queue<int>heap;
        for(auto x:input){
            if(heap.size()<k||heap.top()>x)heap.push(x);
            if(heap.size()>k)heap.pop();
        }
        vector<int>res;
        while(heap.size()){
            res.push_back(heap.top());
            heap.pop();
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

 

posted @ 2019-07-08 19:54  YF-1994  阅读(133)  评论(0编辑  收藏  举报