描述
給一個單詞列表,求出這個列表中出現頻次最高的K個單詞。
你需要按照單詞的詞頻排序後輸出,越高頻的詞排在越前面。如果兩個單詞出現的次數相同,則詞典序小的排在前面。
樣例
給出單詞列表:
[
"yes", "lint", "code",
"yes", "code", "baby",
"you", "baby", "chrome",
"safari", "lint", "code",
"body", "lint", "code"
]
如果 k = 3, 返回 [“code”, “lint”, “baby”]。
如果 k = 4, 返回 [“code”, “lint”, “baby”, “yes”]。
挑戰
用 O(n log k)的時間和 O(n) 的額外空間完成。
思路
構建堆,元素
#ifndef C471_H
#define C471_H
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<queue>
#include<functional>
using namespace std;
//出現次數越多越靠前,出現次數相同按字典序
struct cmp{
bool operator()(pair<int, string> a, pair<int, string> b)
{
if (a.first != b.first)
{
return a.first < b.first;
}
else
return a.second>b.second;
}
};
class Solution {
public:
/**
* @param words: an array of string
* @param k: An integer
* @return: an array of string
*/
vector<string> topKFrequentWords(vector<string> &words, int k) {
// write your code here
if (words.empty())
return words;
vector<string> res;
if (k <= 0)
return res;
//規範k的值
if (k > words.size())
k = words.size();
map<string, int> m;//存放字符串及其出現次數
priority_queue<pair<int, string>, vector<pair<int, string>>, cmp> que;//構建符合題意的堆
for (auto c : words)
m[c]++;
//將所有的<字符串,出現次數>放入堆中
for (auto t : m)
{
pair<int, string> temp = make_pair(t.second, t.first);
que.push(temp);
}
//求堆頂的前k個值
for (int i = 0; i < k; ++i)
{
res.push_back(que.top().second);
que.pop();
}
return res;
}
};
#endif