最小的K个数 -C
题目描述 : ------------------------------------------------------------
给定一个数组,找出其中最小的K个数。例如数组元素是4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
0 <= k <= input.length <= 10000
0 <= input[i] <= 10000
输入样例1 : ------------------------------------------------------------
[4,5,1,6,2,7,3,8],4
返回值1 : ------------------------------------------------------------
[1,2,3,4]
返回最小的4个数即可,返回[1,3,2,4]也可以
输入样例2 : ------------------------------------------------------------
[1],0
返回值2 : ------------------------------------------------------------
[]
// 勇士写法
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
sort(input.begin(), input.end());
return vector<int>(input.begin(), input.begin() + k);
}
};
// 利用最大堆
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
priority_queue<int, vector<int>> maxHeap;
vector<int> res;
if (k==0 || k > input.size())
return res;
for (int val : input)
if (maxHeap.size() < k) {
maxHeap.push(val);
}
else if (val < maxHeap.top()) {
maxHeap.pop();
maxHeap.push(val);
}
while (!maxHeap.empty()) {
res.push_back(maxHeap.top());
maxHeap.pop();
}
return res;
}
};
// 快排
class Solution {
public:
int quickSort(vector<int>& v, int left, int right) {
int midVal = v[right - 1];
int i = left;
for (int j = left; j < right - 1; j++)
if (v[j] < midVal)
swap(v[i++], v[j]);
swap(v[i], v[right - 1]);
return i;
}
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
vector<int> res;
if (k==0 || k > input.size())
return res;
int left = 0, right = input.size();
while (left < right) {
int p = quickSort(input, left, right);
if (p + 1 == k)
return vector<int>(input.begin(), input.begin() + k);
else if (p + 1 < k)
left = p + 1;
else
right = p;
}
return res;
}
};