C++ solution using priority queue


  • 1
    S
    class mycompare{
    public:
        bool operator()(int a, int b){
            return a>b;
        }
    };
    
    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            priority_queue<int, vector<int>, mycompare> pq;
            for(int i=0; i<k; i++) pq.push(nums[i]);
            for(int i=k; i<nums.size(); i++){
                if(nums[i]>pq.top()){
                    pq.pop();
                    pq.push(nums[i]);
                }
            }
            
            return pq.top();
        }
    };
    

    The time complexity is O(nlogk) right?


Log in to reply
 

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