My very easy understanding c++ solution


  • 1
    Z
    class Solution {
    public:
        map<int,int> myMap;        
        struct CmpByValue //this Compair construct is used to sort the pair by pair.second().
        {  
            bool operator()(const pair<int,int>& l, const pair<int,int>& r) 
            {  
              return l.second > r.second;  
            }
        }; 
        vector<int> topKFrequent(vector<int>& nums, int k) 
        {
            for(auto i=nums.begin();i!=nums.end();i++)
            {
                if(myMap.find(*i)!=myMap.end())
                {
                   myMap[*i]++;
                }
                else
                {
                   myMap[*i]=1;
                }
            }
            vector<pair<int,int>> name_score_vec(myMap.begin(), myMap.end());  
            sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());//排序
            vector<int> vec;
            for(int j=0;j<k;j++)
            {
                vec.push_back(name_score_vec[j].first);
            }
            return vec;
    
        }
    };

  • 0
    L

    zmy235, have u seen the note which says "Your algorithm's time complexity must be better than O(n log n)"? if you use sort, the time complexity will be not right.


Log in to reply
 

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