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:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters.

 

Follow up:

  1. 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);
        }
    };
};

 

posted @ 2018-06-13 04:45  妖域大都督  阅读(94)  评论(0编辑  收藏  举报