5.查找最小的k 个元素

时间:2022-12-03 15:46:35
题目:输入n 个整数,输出其中最小的k 个。

例如输入1,2,3,4,5,6,7 和8 这8 个数字,则最小的4 个数字为1,2,3 和4。


答案:

//20121124
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

using namespace std;

int main()
{
	int k;
	cout<<"Type in the K you want"<<endl;
	cin>>k;
	int n=0;
	char c;
	vector<int> vi;
	while (1)
	{
		cin>>c;
		if (c=='#')
		{
			break;
		}
		n=c-0x30;
		if (vi.size()<k)
		{
			vi.push_back(n);
		}
		else
		{
			make_heap(vi.begin(),vi.end(),greater<int>());
			if (n<vi[k-1])
			{
				vi.pop_back();
				vi.push_back(n);
			}
		}
	}
	cout<<"The K min:"<<endl;
	make_heap(vi.begin(),vi.end());
	sort_heap(vi.begin(),vi.end());
	vector<int>::iterator itor,endor;
	endor=vi.end();
	for (itor=vi.begin();itor!=endor;itor++)
	{
		cout<<*itor<<"  ";
	}

	return 0;
}