最小的k个数

一、利用快排的方法实现

#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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值