leetcode692 Top K Frequent Words

思路:

堆。
实现:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 class Solution 
 5 {
 6 public:
 7     inline bool cmp(pair<int, string> a, pair<int, string> b)
 8     {
 9         if (a.first > b.first) return true;
10         if (a.first == b.first && a.second < b.second) return true;
11         return false;
12     }
13     struct cmp1
14     {
15         bool operator()(const pair<int, string>& a, const pair<int, string>& b) const
16         {
17             if (a.first > b.first) return true;
18             if (a.first == b.first && a.second < b.second) return true;
19             return false;
20         }
21     };
22     vector<string> topKFrequent(vector<string>& words, int k) 
23     {
24         unordered_map<string, int> mp;
25         for (auto it : words) mp[it]++;
26         priority_queue<pair<int, string>, vector<pair<int, string>>, cmp1> q;
27         int cnt = 0;
28         for (auto it : mp)
29         {
30             pair<int, string> tmp(it.second, it.first);                
31             if (cnt < k) 
32             {
33                 q.push(tmp);                 
34             }
35             else if (cmp(tmp, q.top())) 
36             { 
37                 q.push(tmp);                
38                 q.pop(); 
39             }            
40             cnt++;
41         }
42         vector<string> ret;
43         while (!q.empty()) 
44         {
45             ret.push_back(q.top().second); q.pop(); 
46         }        
47         reverse(ret.begin(), ret.end());
48         return ret;                     
49     }
50 };
51 int main()
52 {
53     vector<string> v = {"i", "love", "leetcode", "i", "love", "coding"};
54     vector<string> ret = Solution().topKFrequent(v, 2);
55     for (auto it : ret)
56     {
57         cout << it << " ";
58     }
59     cout << endl;
60     return 0;
61 }

 

转载于:https://www.cnblogs.com/wangyiming/p/7662859.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值