typedef pair<string, int> Node; // 这个Node也是为了排序准备的,没人喜欢瞎费功夫
// debug是为了显示中间结果, 看看有没有出问题, 对核心代码运行没有影响
// 这个函数很重要, 因为我们的排序都是基于这个原则
// 如果两个单词的频率都相同的话, 我们要按照字符顺序进行排序
// 如果频率不相同的话, 直接按频率大小由大到小排序
bool compare2(const Node& node1, const Node& node2) {
if (node1.second == node2.second)
return node1.first < node2.first;
return node1.second > node2.second;
}
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
// 首先统计词频
vector<string> ans;
map<string,int> word_counts;
for (int i = 0; i < words.size(); i++) {
word_counts[words[i]]++;
}
// 将单词和相应的词频打包成pair,放到nodeVec中, 主要是为了排序, 不然我才懒得倒腾呢
vector<Node> nodeVec;
for (const auto& item : word_counts) {
nodeVec.push_back(Node(item.first, item.second));
}
#if Debug == 0:
cout << "Debug Test" << endl;
for (const auto& item : nodeVec) {
cout << item.first << "--->" << item.second << endl;
}
#endif
// 然后进行排序
sort(nodeVec.begin(), nodeVec.end(),compare2);
#if Debug == 0:
for (auto item : nodeVec) {
cout << item.first << "--->" << item.second << endl;
}
#endif
// 最后进行输出
for (int i = 0; i < k && i < nodeVec.size(); i++) {
ans.push_back(nodeVec[i].first);
}
return ans;
}
};
leetcode692. 前K个高频单词
最新推荐文章于 2023-12-05 13:26:26 发布