当前位置:网站首页>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;
}
};
如有错误,多多指教
边栏推荐
- Web-based meal ordering system in epidemic quarantine area
- 地下管廊可视化管理系统搭建
- 电脑桌面删除的文件回收站没有,电脑上桌面删除文件在回收站找不到怎么办
- 定时器,同步API和异步API,文件系统模块,文件流
- 关于科研学习中的几个问题:如何看论文?如何评价工作?如何找idea?
- 学习Apache ShardingSphere解析器源码(一)
- 如何做专利挖掘,关键是寻找专利点,其实并不太难
- Easy-to-use translation plug-in - one-click automatic translation plug-in software
- ROS Experiment Notes - Validation of UZH-FPV Dataset
- Multilingual Translation - Multilingual Translation Software Free
猜你喜欢
随机推荐
Mysql. Slow Sql
Part of the reserve bank is out of date
Easy-to-use translation plug-in - one-click automatic translation plug-in software
【C语言】数据储存详解
Which foreign language journals and conferences can be submitted for software engineering/system software/programming language?
11. Custom Converter
Mysql.慢Sql
15. 拦截器-HandlerInterceptor
Which translation software is more accurate [Free]
图片懒加载(纯手写)
“蔚来杯“2022牛客暑期多校训练营4 ADHK题解
YOLOv5的Tricks | 【Trick11】在线模型训练可视化工具wandb(Weights & Biases)
14. Thymeleaf
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 2 DGHJKL Problem Solution
Three-column layout implementation
YOLOv5的Tricks | 【Trick10】从PyTorch Hub加载YOLOv5
Jvm.分析工具(jconsole,jvisualvm,arthas,jprofiler,mat)
ROS Experiment Notes - Validation of UZH-FPV Dataset
虚拟电厂可视化大屏,深挖痛点精准减碳
定时器,同步API和异步API,文件系统模块,文件流