码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode692 Top K Frequent Words

时间:2017-10-13 20:13:06      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:for   while   public   top k   ret   priority   nbsp   ace   top   

思路:

堆。
实现:

 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 }

 

leetcode692 Top K Frequent Words

标签:for   while   public   top k   ret   priority   nbsp   ace   top   

原文地址:http://www.cnblogs.com/wangyiming/p/7662859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!