主要是对次数进行排序,然后去前几个最大次数的值,输出即可

 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;
}
};

最新文章

  1. Apache service named reported the following error(OS 10055)由于系统缓冲区空间不足或队列已满解决办法?
  2. 关于CDN的认识
  3. Chrome Dev Tools :成为更高效的开发人员
  4. Deep learning:四十三(用Hessian Free方法训练Deep Network)
  5. oop、try_except、单例模式
  6. 【iCore3双核心板】扩展引脚分布
  7. c#Enum的用法
  8. 队列工厂之RabbitMQ
  9. Java基础语法&lt;十一&gt; 异常 断言 日志 调试
  10. Linux用户登录记录日志和相关查看命令汇总
  11. Android Studio下导出jar包和aar包
  12. 解析xml字符串时报“前言中不允许有内容”错误。
  13. ABP新增模块可能遇到的问题
  14. Java 平时作业五
  15. 关于java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to 实体类
  16. go微服务框架go-micro深度学习(一) 整体架构介绍
  17. JS 8-5 OOP 实现继承的方式
  18. Vue基础进阶 之 计算属性的使用
  19. PDO添加数据的预处理语句
  20. java的代理和动态代理简单测试

热门文章

  1. MySQL存储过程(批量生成论坛中发帖、回帖、主题等数据)
  2. 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
  3. Ubuntu 16.04下Java环境安装与配置
  4. 线程锁(互斥锁Mutex)
  5. WINDOWS-API:取得当前用户账户名-GetUserName
  6. Vue的安装并在WebStorm中运行
  7. web框架 http协议
  8. 常用JavaScript正则表达式整理
  9. 一段式fsm
  10. 小数据池 is 和 ==的区别