算法中使用到了堆,即stl中的multiset。
#include <iostream>
#include <vector>
#include <set>
using namespace std;
typedef multiset<int, greater<int>> IntHeap;
void FindKLeastNumbers(
const vector<int>& data,
IntHeap& leastNumbers,
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 (leastNumbers.size()<k)
{
leastNumbers.insert(*iter);
}
else
{
IntHeap::iterator iterFirst=leastNumbers.begin();
if (*iter<*iterFirst)
{
leastNumbers.erase(iterFirst);
leastNumbers.insert(*iter);
}
}
}
}
int main()
{
vector<int> data;
data.push_back(7);
data.push_back(2);
data.push_back(8);
data.push_back(1);
data.push_back(5);
data.push_back(3);
data.push_back(6);
data.push_back(-4);
IntHeap leastNumbers;
FindKLeastNumbers(data, leastNumbers, 4);
IntHeap::iterator iter=leastNumbers.begin();
for (; iter!=leastNumbers.end(); ++iter)
{
cout<<*iter<<'\t';
}
cout<<endl;
return 0;
}
来源:https://www.cnblogs.com/enterBeijingThreetimes/archive/2010/08/11/1797359.html