当前位置:网站首页>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;
}
};
如有错误,多多指教
边栏推荐
- Special class and type conversion
- I caught a 10-year-old Ali test developer, and after talking about it, I made a lot of money...
- HGAME 2022 Week1 writeup
- SQL injection base - order by injection, limit, wide byte
- [C language] First understanding of pointers
- How to recover data from accidentally deleted U disk, how to recover deleted data from U disk
- 有哪些可以投稿软件工程/系统软件/程序设计语言类外文期刊、会议?
- 如何做专利挖掘,关键是寻找专利点,其实并不太难
- Mysql. Slow Sql
- [Excel knowledge and skills] Convert "false" date to "true" date format
猜你喜欢
随机推荐
SAS data processing technology (1)
[21天学习挑战赛——内核笔记](五)——devmem读写寄存器调试
CF1427F-Boring Card Game【贪心】
给肯德基打工的调料商,年赚两亿
Why do programming languages have the concept of variable types?
[C language] First understanding of pointers
图像识别和语义分割的区别
[数据可视化] 图表设计原则
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?
IEEE的论文哪里可以下载?
14. Thymeleaf
15. 拦截器-HandlerInterceptor
【C语言】猜数字游戏的实现
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 2 DGHJKL Problem Solution
HGAME 2022 Week1 writeup
如何判断一个数为多少进制?
缓存知识总结
Software protection scenario of NOR FLASH flash memory chip ID application
地下管廊可视化管理系统搭建
[C language] Detailed explanation of data storage







