C++ Solution with min heap


  • 0
    Y

    STL priority_queue is max heap. To define a min heap, use greater<int> as comparator.

    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            
            priority_queue<int, vector<int>, greater<int>> pq;
            for (int i=0; i<nums.size(); i++) {
                pq.push(nums[i]);
                if (pq.size() > k) {
                    pq.pop();
                }
            }
            return pq.top();
            
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.