C++ solutions based on Priority queues


  • 0
    A
    struct comp
    {
        bool operator()(pair<int,int> x,pair<int,int> y)
        {
            return x.first < y.first;
        }
    };
    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
            int i,j,n,cnt,ele;
            n= nums.size();
            sort(nums.begin(),nums.end());
            cnt = 1;
            ele = nums[0];
            priority_queue< pair<int,int> , vector<pair<int,int> > ,comp> frequent; 
            for(i=1;i<n;i++)
            {
                if(nums[i] == ele)
                    cnt ++;
                else
                {
                    frequent.push(make_pair(cnt,ele));
                    cnt = 1;
                    ele = nums[i];
                }
            }
            frequent.push(make_pair(cnt,ele));
            vector<int> topK;
            while(k--)
            {
                topK.push_back(frequent.top().second);
                frequent.pop();
            }
            return topK;
        }
    };
    

Log in to reply
 

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