My C++ code (38ms)


  • 0
    B
    class Solution {
    public:
        struct kv{
            int key;
            int value;  
            bool operator <(const kv& k)const
            {
                return key>k.key;
            }
        };
        vector<int> topKFrequent(vector<int>& nums, int k) {
            unordered_map<int,int> umii;
            for(int x:nums)
                umii[x]++;
            int size=umii.size();
            vector<kv> tmp(size);
            int i=0;
            for(auto x:umii)
            {
                tmp[i].key=x.second;
                tmp[i].value=x.first;
                i++;
            }
            sort(tmp.begin(),tmp.end());
            vector<int> ret;
            for(int i=0;i!=k;i++)
                ret.push_back(tmp[i].value);
            return ret;
        }
    };

Log in to reply
 

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