面试题30_相关题目(最小的k个数_方法二)

来源:互联网 发布:大数据时代的算法 编辑:程序博客网 时间:2024/05/20 19:48

代码示例:

#include<iostream>#include<set>#include<iterator>#include<functional>  #include <algorithm>  using namespace std;typedef multiset<int, greater<int> > IntSet;typedef multiset<int, greater<int> >::iterator  setIterator;void FindKSmall(int a[], int n, int k,IntSet&res){if (a == NULL || n <= 0 || k > n||k<=0)return;res.clear();int index;for (int index = 0; index < n; index++){if (res.size() < k){res.insert(a[index]);}else{setIterator it = res.begin();if (a[index] < *it){res.erase(it);res.insert(a[index]);}}}}int main(){const int n = 10;int k = 5;int a[n] = { 7, 3, 2, 6, 9, 0, 0, 10, 32, 5 };cout << "原数组:";for (int i = 0; i < n; i++)cout << a[i] << " ";cout << endl;IntSet res;cout << "最小的" << k << "个数:";FindKSmall(a, n, k,res);for (setIterator it=res.begin(); it!=res.end(); it++)cout << *it << " ";cout << endl;}