用容量为K的最小堆来存储最大的K个数,最小堆的堆顶元素就是最大K个数中最小的一个。每次考虑一个新的元素时,将其与堆顶的元素进行比较,只有当它大于堆顶元素时,才用其替换堆顶元素,并更新最小堆。时间复杂度为O(N*logK)。
找出最大的K个数方法是建立一个有K个数的最小堆。
- #include <iostream>
- #include <vector>
- #include <set>
- using namespace std;
- typedef multiset< int,less<int> > INTHEAP;
- void FindGreatestNum(vector<int>& iArray, const unsigned int num, INTHEAP& pRes)
- {
- pRes.clear();
- if(iArray.empty() || num <= 0)
- {
- return;
- }
- vector<int>::iterator iter = iArray.begin();
- while(iter != iArray.end())
- {
- if(pRes.size() < num)
- {
- pRes.insert(*iter);
- }
- else
- {
- INTHEAP::iterator pIter = pRes.begin();
- if(*iter > *pIter)
- {
- pRes.erase(pIter);
- pRes.insert(*iter);
- }
- }
- iter ++;
- }
- }
- int main()
- {
- int iArray[] = {1,6,9,0,2,8,12,77,90,54,78,92,23,34,56,76,91};
- int len = sizeof( iArray ) / sizeof( int );
- const unsigned int num = 7;
- vector<int> nArray(iArray, iArray + len);
- INTHEAP pRes;
- FindGreatestNum(nArray, num, pRes);
- INTHEAP::iterator iter = pRes.begin();
- while(iter != pRes.end())
- {
- cout<<*iter<<" ";
- iter ++;
- }
- cout<<endl;
- return 0;
- }
同理:找出最小的K个数方法是建立一个有K个数的最大堆。
- #include <iostream>
- #include <set>
- #include <vector>
- using namespace std;
- typedef multiset<int, greater < int > > intHeap;
- void FindKLeastNumbers(vector< int >& iArray,const unsigned int num,intHeap& pResult)
- {
- pResult.clear();
- if(iArray.empty() || num <= 0)
- {
- return;
- }
- for(vector<int>::iterator iter = iArray.begin(); iter != iArray.end(); iter ++)
- {
- if(pResult.size() < num)
- {
- pResult.insert(*iter);
- }
- else
- {
- multiset<int, greater<int> >::iterator pIter = pResult.begin();
- if(*iter < *(pResult.begin()))
- {
- pResult.erase(pIter);
- pResult.insert(*iter);
- }
- }
- }
- }
- int main()
- {
- int iArray[] = {1,9,7,8,5,3,9,4,2};
- int len = sizeof( iArray ) / sizeof( int );
- vector< int > nArray(iArray, iArray + len);
- const unsigned int num = 4;
- intHeap pResult;
- FindKLeastNumbers(nArray, num, pResult);
- multiset<int, greater<int> >::iterator iter = pResult.begin();
- while(iter != pResult.end())
- {
- cout<<*iter<<" ";
- iter ++;
- }
- cout<<endl;
- return 0;
- }