欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > 前K个高频单词 C++

前K个高频单词 C++

2025/3/17 9:55:54 来源:https://blog.csdn.net/2403_85903590/article/details/141759229  浏览:    关键词:前K个高频单词 C++

给定一个单词列表 words 和一个整数 k ,返回前 k 个出现次数最多的单词。

返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率, 按字典顺序 排序。

示例 1:

输入: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。注意,按字母顺序 "i" 在 "love" 之前。

示例 2:

输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,出现次数依次为 4, 3, 2 和 1 次。
class Solution {
public:vector<string> topKFrequent(vector<string>& words, int k) {map<string,int>countMap;for(auto e:words){countMap[e]++;} //1.将pair<string,int>键值对放到vector中,用sort排序,还要一个int比较仿函数,排完了,还需要对次数相同的按字母排//2.还是用multimap排multimap<int,string,greater<int>>sortMap;for(auto kv :countMap){sortMap.insert(make_pair(kv.second,kv.first));}vector<string> v;for(auto e:sortMap){v.push_back(e.second);if(--k==0)break;}    return v;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词