Skip to content

Kth Largest Element in an Array

leetcode leetcode

c++

    string kthLargestNumber(vector<string>& nums, int k) {
        auto compare = [](const string& a, const string& b) {
            if (a.size() != b.size()) return a.size() > b.size();
            return a > b;
        };
        std::priority_queue<string, vector<string>, decltype(compare)> pq;
        for (string s : nums) {
            if (pq.size() < k || compare(s, pq.top())) pq.push(s);
            if (pq.size() > k) pq.pop();
        }
        return pq.top();
    }