最小的k个数
输入n个整数,找出其中最小的k个数。
注意:
数据保证k一定小于等于输入数组的长度;
输出数组内元素请按从小到大顺序排序;
样例
输入:[1,2,3,4,5,6,7,8] , k=4
输出:[1,2,3,4]
优先级队列
时间复杂度O(nlogn)
class Solution {
public List<Integer> getLeastNumbers_Solution(int [] input, int k) {
//创建一个大顶堆,保存k个元素,如果元素比堆顶小,那么就把元素放进去,把堆顶干掉
priority_queue <int> heap;
for(auto x : input) {
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;
}
}