692. Top K Frequent Words
Posted yaoyudadudu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了692. Top K Frequent Words相关的知识,希望对你有一定的参考价值。
问题描述:
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 Output: ["i", "love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 Output: ["the", "is", "sunny", "day"] Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Input words contain only lowercase letters.
Follow up:
- Try to solve it in O(n log k) time and O(n) extra space.
解题思路:
1.遍历数组用hashmap存储string和其出现的频率
2.在c++中hashmap是用pair存储的key 和 value的键值对,我们可以用struct cmp重写比较器
3.创建最大堆,将pair压入堆中
4.从堆中取出前k个值
需要注意的是:
重写比较器时要考虑频率相等的情况,这里要求按字母顺序输出。
代码:
class Solution { public: vector<string> topKFrequent(vector<string>& words, int k) { unordered_map<string, int> m; priority_queue<pair<string,int>, vector<pair<string, int>>, cmp > h; for(string w : words){ m[w]++; } for(auto p : m){ h.push(p); } vector<string> ret; for(int i = 0; i < k; i++){ ret.push_back(h.top().first); h.pop(); } return ret; } private: struct cmp{ bool operator() (const pair<string, int> &p1, const pair<string,int> &p2){ return p1.second < p2.second || (p1.second==p2.second && p1.first> p2.first); } }; };
以上是关于692. Top K Frequent Words的主要内容,如果未能解决你的问题,请参考以下文章
347. Top K Frequent Elements/692. Top K Frequent Words