347. Top K Frequent Elements【M】【VIP】【字典排序】
2016-05-09 14:58
507 查看
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Subscribe to see which companies asked this question
这个其实挺简单,就是用hash,然后再排序
For example,
Given
[1,1,1,2,2,3]and k = 2, return
[1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Subscribe to see which companies asked this question
这个其实挺简单,就是用hash,然后再排序
class Solution(object): def topKFrequent(self, nums, k): dic = {} for i in nums: dic[i] = dic.get(i,0) + 1 #print dic.items() l = sorted(dic.iteritems(),key = lambda d:d[1], reverse = True) res = [] for i in xrange(k): res += l[i][0], return res
相关文章推荐
- 347. Top K Frequent Elements
- [BS-17] iOS开发-Alpha,Hidden和Opaque区别
- Installation error: INSTALL_FAILED_UID_CHANGED解决方案
- 第九章 UITableView编辑模式笔记
- 限制UITextView输入字数(兼容iOS7)
- UIInterfaceOrientation和UIDeviceOrientation的区别
- UIGraphics 绘制饼图
- UE4 减少APK包的大小
- JDBC Request的用法
- iOS之UI学习-UITextField属性篇
- vue中v-bind:class动态添加class
- UIGraphics 向图片上写字
- 限制UITextField只能输入数字
- UITextView 文字莫名其妙垂直居中解决办法
- ${pageContext.request.contextPath} JSP取得绝对路径
- 通过layout实现可拖拽自动排序的UICollectionView
- 通过UITableViewCell获取indexPath
- iOS UICollectionView 瀑布流
- CodeForces 590B Chip 'n Dale Rescue Rangers
- UIImagePickerController