One line C++ solution


  • 0
    L
    class Solution { public: int findKthLargest(vector<int>& nums, int k) { priority_queue<int, vector<int>, function<bool(int, int)>> pq( [](const int & a, const int & b) { return a >= b; }); for (auto n : nums) { pq.emplace(n); if (pq.size() > k) { pq.pop(); } } return pq.top(); } };
    

    Now joke aside, here is my twelve line solution using the priority_queue from STL.

    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            priority_queue<int, vector<int>, function<bool(int, int)>> pq(
                [](const int & a, const int & b) { return a >= b; });
            for (auto n : nums) {
                pq.emplace(n);
                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.