当前位置:网站首页>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;
}
};
如有错误,多多指教
边栏推荐
- ROS实验笔记之——安装QPEP以及Intel-MKL
- 电脑桌面删除的文件回收站没有,电脑上桌面删除文件在回收站找不到怎么办
- Mysql. Slow Sql
- [Excel知识技能] 将数值格式数字转换为文本格式
- 分布式.性能优化
- 只会懒汉式和饿汉式 你还不懂单例模式!
- Which foreign language journals and conferences can be submitted for software engineering/system software/programming language?
- SQL注入基础
- Why do programming languages have the concept of variable types?
- ROS Experiment Notes - Validation of UZH-FPV Dataset
猜你喜欢
翻译软件哪个准确度高【免费】
Mysql. Slow Sql
虚拟电厂可视化大屏,深挖痛点精准减碳
2. 依赖管理和自动配置
Design and implementation of flower online sales management system
2. Dependency management and automatic configuration
How to recover data from accidentally deleted U disk, how to recover deleted data from U disk
There is no recycle bin for deleted files on the computer desktop, what should I do if the deleted files on the desktop cannot be found in the recycle bin?
鲲鹏编译调试及原生开发工具基础知识
Lens filter---about day and night dual-pass filter
随机推荐
SAS data processing technology (1)
如何判断一个数为多少进制?
YOLOv5的Tricks | 【Trick11】在线模型训练可视化工具wandb(Weights & Biases)
promise详解
C语言篇,操作符之 移位运算符(>>、<<)详解
HGAME 2022 Week1 writeup
Summary of Confused Knowledge Points for "High Items" in the Soft Examination in the Second Half of 2022 (2)
[Data Visualization] Chart Design Principles
编程语言为什么有变量类型这个概念?
Software protection scenario of NOR FLASH flash memory chip ID application
【C语言】猜数字游戏的实现
Introduction to Qt (6) - Implementation of the lottery system
【js】获取当前时间的前后n天或前后n个月(时分秒年月日都可)
HGAME 2022 Final Pokemon v2 writeup
Cache knowledge summary
学习Apache ShardingSphere解析器源码(一)
【redis】发布和订阅消息
关于科研学习中的几个问题:如何看论文?如何评价工作?如何找idea?
特殊类与类型转换
[C language] Implementation of guessing number game