Scribbling

[C++] priority queue (vector<int>) with comparator 본문

Computer Science/C++

[C++] priority queue (vector<int>) with comparator

focalpoint 2023. 8. 18. 05:52

 

LeetCode 347. Top K Frequent Elements

https://leetcode.com/problems/top-k-frequent-elements/

 

Top K Frequent Elements - LeetCode

Can you solve this real interview question? Top K Frequent Elements - Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.   Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]

leetcode.com

struct my_comparator
{
    bool operator()(std::vector<int> const& a, std::vector<int> const& b) const
    {
        // smallest to top (min heap)
        return a[0] > b[0];
    }
};

using custom_priority_queue = std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, my_comparator>;


class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> counter;
        for (auto num : nums) {
            counter[num]++;
        }
        custom_priority_queue pq;
        for (auto e : counter) {
            vector<int> tmp;
            tmp.push_back(e.second);
            tmp.push_back(e.first);
            pq.push(tmp);
            if (pq.size() > k) {
                pq.pop();
            }
        }
        vector<int> ret;
        while (!pq.empty()) {
            vector<int> tmp = pq.top();
            pq.pop();
            ret.push_back(tmp[1]);
        }
        return ret;
    }
};