用priority_queue實現找出陣列中前K個大的元素
阿新 • • 發佈:2019-01-10
// 利用priority_queue查詢陣列中最大的K個數.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<algorithm> #include<iostream> #include<functional> #include<queue> #include<vector> using namespace std; void findBigKElement(int A[], int len, int K, int output[]) { priority_queue<int, vector<int>, greater<int> > pq; int idx = 0; for (; idx < K; idx++) { pq.push(A[idx]); } for (; idx < len; idx++) { pq.push(A[idx]); pq.pop(); } cout << "output the the Bigger K number" << endl; for (int i = 0; i < K; i++) { cout << pq.top() << " "; output[idx] = pq.top(); pq.pop(); } } void findBigKElement2(int A[], int len, int K, int output[]) { std::vector<int> vector(A, A+K); std::make_heap(vector.begin(), vector.end(), greater<int>()); for (int idx = K; idx < len; idx++) { vector.push_back(A[idx]); std::push_heap(vector.begin(),vector.end(), greater<int>()); std::pop_heap(vector.begin(), vector.end(), greater<int>()); vector.pop_back(); } std::sort_heap(vector.begin(), vector.end(), greater<int>()); int num = vector.front(); cout << "output the the Bigger K number" << endl; std::vector<int>::iterator itr = vector.begin(); for (int i = 0; i < K; i++) { cout << *itr << " "; output[i] = (*itr); ++itr; } cout << endl; } int _tmain(int argc, _TCHAR* argv[]) { int Arr[] = {1,4,6,8,3,5,7,9,0,2}; int B[5] = {0}; findBigKElement2(Arr, 10, 5, B); return 0; }