当前位置:网站首页>leetcode 前K个高频单词
leetcode 前K个高频单词
2022-08-10 23:53:00 【老鱼37】
思路:
1.运用unordered_map容器将words存放map中,相同字符串不会重复插入,但是value值会递增-----计算单词的出现频率。
2.创建一个pair<string,int>数组 将map中的数据放入并 排好序,按照字典序的方式排序字符串
3.创建string字符数组 然后将前K个高频单词存放 最后返回即可
class Solution {
public:
static bool cmp(const pair<string,int>&a,const pair<string,int>&b)
{
if(a.second>b.second)
{
return true;
}
if(a.second==b.second)
{
if(a.first<b.first)
{
return true;
}
}
return false;
}
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int>ppt;
//记录每个单词出现的频率
for(auto&ch:words)
{
++ppt[ch];
}
//创建一个vector<string,int>容器来接收map中的数据 进行sort
vector<pair<string,int>>ps(ppt.begin(),ppt.end());
//重新排序
sort(ps.begin(),ps.end(),cmp);
//创建一个字符数组
vector<string>ans;
auto it =ps.begin();
while(k--)
{
ans.emplace_back(it->first);
it++;
}
return ans;
}
};
如有错误,多多指教
边栏推荐
- 【爬虫】scrapy创建运行爬虫、解析页面(嵌套url)、自定义中间件(设置UserAgent和代理IP)、自定义管道(保存到mysql)
- iNFTnews | In the Web3 era, users will have data autonomy
- Special class and type conversion
- [Excel知识技能] 将文本型数字转换为数值格式
- I caught a 10-year-old Ali test developer, and after talking about it, I made a lot of money...
- 5. Lombok
- [C language articles] Expression evaluation (implicit type conversion, arithmetic conversion)
- 缓存知识总结
- Qt入门(六)——抽奖系统的实现
- C language% (%d,%c...)
猜你喜欢
“蔚来杯“2022牛客暑期多校训练营2 DGHJKL题解
How to recover data from accidentally deleted U disk, how to recover deleted data from U disk
多语种翻译-多语种翻译软件免费
从0开始设计JVM ,忘记名词跟上思路一次搞懂
14. Thymeleaf
Design and Realization of Employment Management System in Colleges and Universities
翻译软件哪个准确度高【免费】
Which translation software is more accurate [Free]
9. Rest 风格请求处理
Why do programming languages have the concept of variable types?
随机推荐
sqlmap combined with dnslog fast injection
7. yaml
如何做专利挖掘,关键是寻找专利点,其实并不太难
SAS data processing technology (1)
力扣每日一题-第52天-387. 字符串中的第一个唯一字符
电脑桌面删除的文件回收站没有,电脑上桌面删除文件在回收站找不到怎么办
图像识别和语义分割的区别
ROS实验笔记之——安装QPEP以及Intel-MKL
15. 拦截器-HandlerInterceptor
【C语言】猜数字游戏的实现
Multilingual Translation - Multilingual Translation Software Free
Dump文件生成,内容,以及分析
只会懒汉式和饿汉式 你还不懂单例模式!
10. Notes on receiving parameters
11. 自定义转换器
9. Rest style request processing
[Excel知识技能] 将数值格式数字转换为文本格式
[Excel knowledge and skills] Convert text numbers to numeric format
三栏布局实现
服务器小常识