Leetcode-692 Top K Frequent Words(前K个高频单词)

 1 struct cmp
 2 {
 3     bool operator()(const pair<string,int> p1, const pair<string,int> 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 Solution
12 {
13     public:
14         vector<string> topKFrequent(vector<string>& words, int k)
15         {
16             unordered_map<string,int> 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                 else
25                 {
26                     ptr_to_str->second ++;
27                 }
28             }
29 
30             priority_queue<pair<string,int>, vector<pair<string,int>>, cmp> Q;
31             for(auto p:mymap)
32             {
33                 if(Q.size()<k)
34                 {
35                     Q.push(make_pair(p.first,p.second));
36                 }
37                 else
38                 {
39                     if(p.second>Q.top().second || (p.second==Q.top().second && p.first<Q.top().first))
40                     {
41                         Q.pop();
42                         Q.push(make_pair(p.first,p.second));
43                     }
44                 }
45             }
46 
47             vector<string> 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 };

 

posted @ 2018-08-16 10:45  Asurudo  阅读(316)  评论(0编辑  收藏  举报