What's the problem of this code?


  • 0
    Y
    class Solution {
    public:
        struct compare{
            bool fun1(pair<int, int>& p1, pair<int, int>& p2) {
                return p1.second >= p2.second;
            }
        };
        
        vector<int> topKFrequent(vector<int>& nums, int k) {
            unordered_map<int, int> h;
            vector<int> res;
            for(int i = 0;i < nums.size(); ++i){
                h[nums[i]] ++;
            }
            //second and first are the member variables, thus using '.' p.first.
            //auto fun = [](const pair<int,int>& p1, const pair<int,int>& p2) {return p1.second >= p2.second;};
            priority_queue< pair<int,int>, vector<pair<int,int>>, compare> Q;
            
            for(auto p:h){
                Q.push(make_pair(p.first, p.second));   //pair<first, second> first is number,second is the frequency
            }
            
            for(int i = 0;!Q.empty() && i < k; ++i){
                res.push_back(Q.top().second);
                Q.pop();
            }
            return res;
        }
    };
    

    Another question specific to C++ issue.
    Why we cannot use the code as following?

    auto fun = [](const pair<int,int>& p1, const pair<int,int>& p2) {return p1.second >= p2.second;};
            priority_queue< pair<int,int>, vector<pair<int,int>>, fun> Q;
    

    Thanks


Log in to reply
 

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