1. 程式人生 > >692. Top K Frequent Words

692. Top K Frequent Words

int auto shm 思路 pair ring () mes ace

問題描述:

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

692. Top K Frequent Words