最小的k个数
题目
输入n个整数,找出其中最小的k个数。
注意
- 数据保证k一定小于等于输入数组的长度;
- 输出数组内元素请按从小到大顺序排序;
样例
输入:[1,2,3,4,5,6,7,8] , k=4
输出:[1,2,3,4]
题解1
排序即可
class Solution {
public:
vector<int> getLeastNumbers_Solution(vector<int> input, int k) {
sort(input.begin(), input.end());
vector<int> ans;
for (int i = 0; i < k; i ++) ans.push_back(input[i]);
return ans;
}
};
题解2
利用大根堆
class Solution {
public:
vector<int> getLeastNumbers_Solution(vector<int> input, int k) {
priority_queue<int> heap;
for (int i = 0; i < input.size(); i ++) {
heap.push(input[i]);
if (i >= k) heap.pop();
}
vector<int> ans;
while (heap.size()) ans.push_back(heap.top()), heap.pop();
reverse(ans.begin(), ans.end());
return ans;
}
};