前进的道路不是一帆风顺的,要随时迎接挑战,敢于战胜困难!

坚持一下,找人聊聊天,释放一些压力!

 

查找最小的k个元素

算法中使用到了堆,即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;
}

posted on 2010-08-11 15:25  山径山精  阅读(373)  评论(0编辑  收藏  举报

导航