int kthlargest(vector<int>& nums, int k) { // a max heap priority_queue<int> pq(nums.begin(), nums.end()); // remove top k-1 elements for(int i = k - 1; i > 0; i--) { print pq.top(); pq.pop(); }}
For massive data
Use a min Priority Queue to store k elements and discard the minimum whenever the queue is full and the new element is greater
Time: O(nlogk), Space: O(k)
int kthlargest(vector<int>& nums, int k) { // min heap priority_queue<int, vector<int>, greater<int>> pq; for (int i : nums) { if(pq.size() > k && i < pq.top()) continue; pq.push(i); if (pq.size() > k) pq.pop(); } print pq;}