Using priority queue and Map


  • 0
    N
    struct eme{
      int cnt;
      int number;
      bool operator <(const eme &t)const
      {
          return cnt<t.cnt;
      }
    };
    class Solution {
    public:
        vector<int> topKFrequent(vector<int>& nums, int k) {
            priority_queue<eme>pq;
            map<int,int>mp;
            int i,j;
            for(i=0;i<nums.size();i++)
            {
                mp[nums[i]]++;
            }
            for(map<int,int>::iterator it=mp.begin();it!=mp.end();++it)
            {
                eme temp;
                temp.cnt=it->second;
                temp.number=it->first;
                pq.push(temp);
            }
            vector<int>v;
            while(k--)
            {
                v.push_back(pq.top().number);
                pq.pop();
            }
            return v;
        }
    };

Log in to reply
 

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