一、利用快排的方法实现
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <ctime>
using namespace std;
template <typename InIt> void myfunction(InIt str) {
cout<<str<<" ";
}
struct myclass { // function object type:
template <typename InIt> void operator() (InIt i) {
cout << i << " ";
}
} myobject;
template <typename T> class myclass2 {
private:
T elem;
public:
myclass2() : elem(0){}
void operator() (T elem) {
cout<<elem<<" ";
}
};
class Solution {
public:
void GetLeastNumbers(int A[], int length, int k) {
int first = 0, last = length - 1;
int inode = Location(A, first, last);
while (inode != k - 1) {
if (inode > k -1)
{
last = inode - 1;
inode = Location(A, first, last);
}
else
{
first = inode + 1;
inode = Location(A, first, last);
}
}
/*
*三个for_else测试都是通过的
*/
for_each(A, A + k, myobject);
for_each(A, A + k, myfunction<int&>);
for_each(A, A + k, myclass2<int>());
}
int Location(int A[], int first, int last) {
srand((unsigned int)time(NULL));
int irand = first + rand() % (last - first + 1);//在[first, last]产生随机数
swap(A[irand], A[last]);
int small = first - 1;
int index = first;
for (; index != last; index++) {
if (A[index] < A[last]) {
small++;
if (small != index){
swap(A[small], A[index]);
}
}
/*if (A[index] >= A[last]) {
continue;
}
else {
small++;
if (small != index){
swap(A[small], A[index]);
}
}*/
}
small++;
swap(A[small], A[last]);
return small;
}
};
int main(void)
{
Solution s;
int A[8] = {4,5,1,6,2,7,3,8};
s.GetLeastNumbers(A, 8, 4);
return 0;
}
二、利用multiset容器实现
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <set>
#include <functional>
#include <iterator>
using namespace std;
class Solution {
public:
void GetLeastNumbers(vector<int>& array, multiset<int, greater<int> >& mu, int k) {
int count = 0;
for(vector<int>::iterator it = array.begin(); it != array.end(); it++) {
count++;
if (count <= k)
{
mu.insert(*it);
}
else
{
multiset<int, greater<int> >::iterator ve = mu.begin();
if (*it < *ve)
{
mu.erase(ve);
mu.insert(*it);
}
}
}
for (multiset<int, greater<int> >::iterator it = mu.begin(); it != mu.end(); it++) {
cout<<*it<<" ";
}
}
};
int main(void)
{
Solution s;
int A[8] = {4,5,1,6,2,7,3,8};
int k;
cin>>k;
vector<int> arry;
arry.assign(A, A + 8);
multiset<int, greater<int> > mu;
s.GetLeastNumbers(arry, mu, k);
return 0;
}