leetcode 347 priority,map的使用
2024-08-26 14:12:59
主要是对次数进行排序,然后去前几个最大次数的值,输出即可
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
int i;
unordered_map<int,int>p_map;
map<int,int>::iterator it;
for(i=;i<nums.size();i++) {
p_map[nums[i]]++;
}
priority_queue<pair<int,int>>p_queue;
for(it=p_map.begin();it!=p_map.end();it++)
p_queue.push(make_pair(it->second,it->first));
vector<int>num_result;
for(i=;i<=k;i++) {
num_result.push_back(p_queue.top().second);
p_queue.pop();
}
return num_result;
}
};
另一种写法也非常好:http://blog.csdn.net/yzhang6_10/article/details/51388021
class Op{
public:
int Op_count;
int Op_num;
Op(int count,int num) {
Op_count=count;
Op_num=num;
}
bool operator <(const Op&Cpone)const
{
return Op_count>Cpone.Op_count;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
int i;
map<int,int>p_map;
map<int,int>::iterator it;
for(i=;i<nums.size();i++) {
p_map[nums[i]]++;
}
vector<Op>p_queue;
for(it=p_map.begin();it!=p_map.end();it++)
p_queue.push_back(Op(it->second,it->first));
vector<int>num_result;
sort(p_queue.begin(),p_queue.end());
for(i=;i<k;i++)
num_result.push_back(p_queue[i].Op_num); return num_result;
}
};
最新文章
- Apache service named reported the following error(OS 10055)由于系统缓冲区空间不足或队列已满解决办法?
- 关于CDN的认识
- Chrome Dev Tools :成为更高效的开发人员
- Deep learning:四十三(用Hessian Free方法训练Deep Network)
- oop、try_except、单例模式
- 【iCore3双核心板】扩展引脚分布
- c#Enum的用法
- 队列工厂之RabbitMQ
- Java基础语法<;十一>; 异常 断言 日志 调试
- Linux用户登录记录日志和相关查看命令汇总
- Android Studio下导出jar包和aar包
- 解析xml字符串时报“前言中不允许有内容”错误。
- ABP新增模块可能遇到的问题
- Java 平时作业五
- 关于java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to 实体类
- go微服务框架go-micro深度学习(一) 整体架构介绍
- JS 8-5 OOP 实现继承的方式
- Vue基础进阶 之 计算属性的使用
- PDO添加数据的预处理语句
- java的代理和动态代理简单测试
热门文章
- MySQL存储过程(批量生成论坛中发帖、回帖、主题等数据)
- OpenStack安装keyston 错误BError: (pymysql.err.InternalError) (1071, u‘Specified key was too long; max key length is 767 bytes‘) [SQL: u‘\nCREATE TABLE migrate_ver
- Ubuntu 16.04下Java环境安装与配置
- 线程锁(互斥锁Mutex)
- WINDOWS-API:取得当前用户账户名-GetUserName
- Vue的安装并在WebStorm中运行
- web框架 http协议
- 常用JavaScript正则表达式整理
- 一段式fsm
- 小数据池 is 和 ==的区别