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