1 struct cmp 2 { 3 bool operator()(const pairp1, const pair p2) 4 { 5 if(p1.second!=p2.second) 6 return p1.second > p2.second; //second的小值优先 7 return p1.first < p2.first; 8 } 9 };10 11 class Solution12 {13 public:14 vector topKFrequent(vector & words, int k)15 {16 unordered_map mymap;17 for(auto s:words)18 {19 auto ptr_to_str = mymap.find(s);20 if(ptr_to_str==mymap.end())21 {22 mymap.insert(make_pair(s,1));23 }24 else25 {26 ptr_to_str->second ++;27 }28 }29 30 priority_queue , vector >, cmp> Q;31 for(auto p:mymap)32 {33 if(Q.size() Q.top().second || (p.second==Q.top().second && p.first result;48 while(!Q.empty())49 {50 result.emplace_back(Q.top().first);51 Q.pop();52 }53 reverse(result.begin(),result.end());54 return result;55 }56 };