平均复杂度 O(nlogk) 的基于快排的方法
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
#include <algorithm>
#define BUG cout << "here\n";
using namespace std;
const int N = 105;
int a[N] = {4, 5, 1, 6, 2, 7, 3, 8};
int partition(int a[], int left, int right) {
if(left < right) {
int l = left, r = right, x = a[l];
while(1) {
while(l < r && a[r] >= x) r--;
while(l < r && a[l] <= x) l++;
if(l >= r) break;
swap(a[r], a[l]);
}
swap(a[left], a[l]);
return l;
}
else return left;
}
void solve(int* input, int n, int k) {
if(input == NULL || k > n || n <= 0 || k <= 0) {
return;
}
int start = 0;
int end = n - 1;
int index = partition(input, start, end);
while(index != k-1) {
if(index > k-1) {
end = index - 1;
index = partition(input, start, end);
}
else {
start = index + 1;
index = partition(input, start, end);
}
}
for(int i = 0; i < k; i++) {
cout << input[i] << ' ';
}
cout << endl;
}
int main() {
solve(a, 8, 5);
return 0;
}
(堆优化 STL O(nlogk) ) 【STL】
#include <iostream>
#include <string>
#include <cstdio>
#include <set>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
typedef multiset<int, greater<int> > intSet; /// 定义容器的
typedef multiset<int, greater<int> >::iterator setIterator; /// 定义迭代器的
void getLastNumbers(const vector<int>& data, intSet& setK, int k) {
setK.clear();
if(k < 1 || data.size() < k) return;
vector<int>::const_iterator iter = data.begin();
for(;iter != data.end(); ++iter) {
if(setK.size() < k) {
setK.insert(*iter);
}
else {
setIterator iter2 = setK.begin(); // 最大的位置
if(*iter < (*iter2)) {
setK.erase(iter2);
setK.insert(*iter);
}
}
}
setIterator sit = setK.begin();
for(;sit != setK.end(); sit++) {
cout << *sit << ' ';
}
cout << endl;
}
int main() {
vector<int> V;
V.push_back(4); V.push_back(5); V.push_back(1); V.push_back(6);
V.push_back(2); V.push_back(7); V.push_back(3); V.push_back(8);
intSet ms;
getLastNumbers(V, ms, 5);
return 0;
}