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 };

 

转载于:https://www.cnblogs.com/Asurudo/p/9485930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值