作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/top-k-frequent-elements/description/

题目描述

Given a non-empty array of integers, return the k most frequent elements.

For example,

Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

解题方法

把出现次数最大的前k个数输出。

解题方法

字典

这个题要求时间复杂度是O(nlogn),就可以按照出现的次数先排个序,然后找到出现最多的k个就好。Counter类有most_common()函数,能按出现的次数进行排序。返回的是个列表,列表中每个元素都是一个元组,元组的第一个元素是数字,第二个数字是出现的次数。

from collections import Counter
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
counter = Counter(nums).most_common()
return [counter[i][0] for i in range(k)]

优先级队列

使用优先级队列来让出现次数多的优先弹出来,当然需要字典统计次数。

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> m;
for (int n : nums) m[n] ++;
priority_queue<pair<int, int>> p;
for (auto a : m)
p.push({a.second, a.first});
vector<int> res;
for (int i = 0; i < k; i++) {
res.push_back(p.top().second); p.pop();
}
return res;
}
};

日期

2018 年 2 月 8 日
2018 年 12 月 14 日 —— 12月过半,2019就要开始

最新文章

  1. 使用js批量选中功能实现更改数据库中的status状态值(批量展示)
  2. Android 学习笔记
  3. c++ 之 编译期多态&amp;运行期多态
  4. 攻城狮在路上(叁)Linux(二十)--- Linux磁盘格式化
  5. php总结 --- 4. 对象
  6. 每日vim插件--vim中的文本对象及相关插件
  7. BZOJ-1861 Book 书架 Splay
  8. KMP算法初探
  9. python网络编程(六)---web客户端访问
  10. php hook 之简单例子
  11. (转)分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)
  12. bzoj1898
  13. HDU 5723 Abandoned country(最小生成树 + 树形DP)
  14. java常见面试题(一)
  15. for in 中的index
  16. VS 开发必用插件
  17. 牛客国庆集训派对Day3 B Tree
  18. JavaScript+CSS+DIV实现表格变色示例
  19. CentOS系统基础优化16条知识汇总
  20. json字符窜转对象

热门文章

  1. R 多图间距调整
  2. eclipse 配置黑色主题(转载)
  3. 关于ARM的PC指针(什么时候PC+8,PC+4,PC-4,PC-8)转
  4. 8核cpu,,负载
  5. 使用clion阅读eos源码
  6. javaAPI1
  7. Hibernate 总结(转)
  8. virtualBox 系统移植
  9. Activiti工作流引擎使用详解(一)
  10. ssm项目中常用的上传文件