最小的k个数

it2022-05-05  156

输入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; } };

 

转载于:https://www.cnblogs.com/programyang/p/11153400.html

相关资源:各显卡算力对照表!

最新回复(0)