347. Top K Frequent Elements
2016-05-14 21:58
471 查看
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:
•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.
给一个数组和K值,递减输出K个数组中出现频率最高的元素
Answer with python:
elements.
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.
给一个数组和K值,递减输出K个数组中出现频率最高的元素
Answer with python:
Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ new_dict = {} #set a new dic for item in nums: #将数组元素设置为字典的key,value初始化为1 if item not in new_dict: new_dict[item] =1; else: #计算数组内重复元素的个数,设置为字典的值 new_dict[item] +=1; sorted_dict = sorted(new_dict, key=new_dict.get, reverse=True) #以字典内values的大小顺序排列 return sorted_dict[:k] #切片取K个值
相关文章推荐
- Arduino 和 HC-SR04 超声波传感器 测距
- TableView的优化
- iOS应用程序的启动原理-UI进阶
- iOS基础开发UI界面-xib与代码自定义控件的区别
- 一个安卓终端客户端:JuiceSSH
- s5pv210 datasheet_system_BOOTING SEQUENCE
- Android并发编程之Handler,MessageQueue,Looper详解
- vueJs源码解读0-2
- 1101. Quick Sort (25)【快排】——PAT (Advanced Level) Practise
- 1099. Build A Binary Search Tree (30)【二叉树】——PAT (Advanced Level) Practise
- iOS 并行编程:NSOperation Queues
- iOS开发 - 第02篇 - UI进阶 - 03 - TableView Cell
- mysql5.7下的timestampn Error : Invalid default value for 'timestamp'
- 115. Distinct Subsequences dp算法
- 斐波那契数列(Fibonacci sequence)的前200项
- 使用bat对UiAutomator程序进行快速调试
- 使用NGUI模仿制作“切水果”
- ios开发UI系列之使用AutoLayout的几个经典的布局技巧
- 优先队列priority queue
- iOS-UIAlertController的另类使用