题目:输入n个整数,找出其中最小的k个数。
思路:与29题类似。
#include <iostream>
#include <vector>
using namespace std;
int Partition(vector<int> &num, int length, int begin, int end) {
if (num.empty() || length <= 0 || begin < 0 || end >= length)
return -1;
int index = begin;
int small = begin - 1;
while (index < end) {
if (num[index] < num[end]) {
++small;
int temp = num[index];
num[index] = num[small];
num[small] = temp;
}
++index;
}
++small;
int temp = num[small];
num[small] = num[end];
num[end] = temp;
return small;
}
void SmallestK(vector<int> &num, int length, int k) {
if (num.empty() || length <= 0)
return;
int begin = 0;
int end = length - 1;
int index = Partition(num, length, begin, end);
while (index != k - 1) {
if (index > k - 1) {
end = index - 1;
index = Partition(num, length, begin, end);
} else {
begin = index + 1;
index = Partition(num, length, begin, end);
}
}
for (int i = 0; i < k; i++) {
cout << num[i] << " ";
}
cout << endl;
}
int main() {
vector<int> num;
int k;
cin >> k;
int a;
while (cin >> a) {
num.push_back(a);
}
a = num.size();
SmallestK(num, a, k);
for (auto c : num)
cout << c << " ";
cout << endl;
return 0;
}