Find the number of the top K in an array
Examples
Give [3,10,1000,-99,4,100], k = 3.
Back [1000, 100, 10]
Ideas
Build the minimum heap que. Traversal array nums, for element C, if the size of the que is less than k, directly add C; otherwise, compare the size of C and que heap tops, if C is large, to ensure the first k maximum, the top element of the heap pops up, add element C.
#ifndef c544_h #define C544_H #include <iostream> #include <vector> #include <queue> #include <
Functional> using namespace std; Class Solution {public:/** * @param nums:an integer array * @param k:an an integer * @return: the top k L Argest numbers in array */vector<int> TOPK (vector<int> &nums, int k) {//write your code
here if (Nums.empty ()) return nums;
Normalized k value if (K > Nums.size ()) K = Nums.size ();
Priority_queue<int,vector<int>,greater<int>> que;//constructs the smallest heap vector<int> res; When the size of the que is less than k, add the element c//Otherwise, compare the size of the C with the minimum heap heap top value, if C is large, eject the top element of the heap, add element c for (auto C:nums) {if (q
Ue.size () < K) Que.push (c);
else {if (C>que.top ()) {Que.pop ();
Que.push (c);
}
} ///Insert the top element of the heap into the head of the res while (!que.empty ()) {Res.insert (Res.begin (), Que.top ());
Que.pop ();
return res;
}
}; #endif