5.查找最小的k个元素

本文介绍了一种高效查找并返回给定数组中最小的K个整数的算法实现。通过使用最大堆数据结构(在这里表现为逆序多集合),算法能够动态维护一个包含当前最小值的集合,并允许在插入新元素时移除最大值,确保集合大小始终等于K。
摘要由CSDN通过智能技术生成

(05)查找最小的k个元素[折叠]

题目:输入n个整数,输出其中最小的k个。

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


#include <set>
#include <vector>
#include <iostream>

using namespace std;

typedef multiset<int, greater<int> >  IntHeap;

///
// find k least numbers in a vector
///
void findKLeastNumbers
(
	const vector<int>& data,               // a vector of data
	IntHeap& leastNumbers,                 // k least numbers, output
	unsigned int k                              
)
{
	leastNumbers.clear();

	if(k == 0 || data.size() < k)
		return;

	vector<int>::const_iterator iter = data.begin();
	for(; iter != data.end(); ++ iter)
	{
		// if less than k numbers was inserted into leastNumbers
		if((leastNumbers.size()) < k)
			leastNumbers.insert(*iter);

		// leastNumbers contains k numbers and it's full now
		else
		{
			// first number in leastNumbers is the greatest one
			IntHeap::iterator iterFirst = leastNumbers.begin();

			// if is less than the previous greatest number 
			if(*iter < *(leastNumbers.begin()))
			{
				// replace the previous greatest number
				leastNumbers.erase(iterFirst);
				leastNumbers.insert(*iter);
			}
		}
	}
}

int main(){
	vector<int> dates;
	IntHeap leastNumbers;
	int k =4;
	
	dates.push_back(6);
	dates.push_back(9);
	dates.push_back(2);
	dates.push_back(3);
	dates.push_back(1);
	dates.push_back(8);
	dates.push_back(5);
	dates.push_back(7);
	dates.push_back(6);

	findKLeastNumbers(dates,leastNumbers,k);

	IntHeap::iterator iterFirst = leastNumbers.begin();
	for(;iterFirst != leastNumbers.end();iterFirst++){
		cout << *iterFirst << ' ' << endl;
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值