mycode   71.43%

class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums:
return []
from collections import Counter
s = Counter(nums).most_common()
res = []
for val,count in s:
res.append(val)
if len(res) == k:
return res

参考:

思路:

heapq--该模块提供了堆排序算法的实现。堆是二叉树,最大堆中父节点大于或等于两个子节点,最小堆父节点小于或等于两个子节点。

如果需要获取堆中最大或最小的范围值,则可以使用heapq.nlargest() 或heapq.nsmallest() 函数

下面例子中heapq.nlargest的第二个参数遍历,每一个值代入第三个参数中,得到最终用来排序的数组成的列表

import heapq
from pprint import pprint
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
pprint(cheap)
pprint(expensive) """
输出:
[{'name': 'YHOO', 'price': 16.35, 'shares': 45},
{'name': 'FB', 'price': 21.09, 'shares': 200},
{'name': 'HPQ', 'price': 31.75, 'shares': 35}]
[{'name': 'AAPL', 'price': 543.22, 'shares': 50},
{'name': 'ACME', 'price': 115.65, 'shares': 75},
{'name': 'IBM', 'price': 91.1, 'shares': 100}]

遍历每个key,作为第三个参数的参数,得到对应的值,他们组合了用来排序的所有值

import heapq
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not k:
return 0
mydict={}
for i in nums:
if i in mydict:
mydict[i]+=1
else:
mydict[i]=0 return heapq.nlargest(k,mydict.keys(),mydict.get)

最新文章

  1. about Internet protocol
  2. 如果重新设计网络,有没有可能合并IP地址跟MAC地址?
  3. Access restriction : The constructor BASE64Decoder() is not accessible due to restriction on required library
  4. MFC学习 多线程
  5. accordion data-options iconCls
  6. 总结:常用的Linux系统监控命令
  7. ehcache基本原理
  8. IOS--UILabel的使用方法详细
  9. asp.net session的原理
  10. 略懂 MySQL字符集
  11. 敏捷开发每日报告--day4
  12. MinHash 原理
  13. localhost 将您重定向的次数过多
  14. 使用HBuilder+MUI+Flask后端服务器框架+Mongodb数据库开发手机APP
  15. php网站速度性能优化(转)
  16. Web前端性能优化策略
  17. python List的一些相关操作
  18. ArrayList和Array区别
  19. Linux-Linux基础入门
  20. Garbage First(G1)垃圾收集器

热门文章

  1. luogu P1587 [NOI2016]循环之美
  2. 编写python爬虫采集彩票网站数据,将数据写入mongodb数据库
  3. java 导出自定义样式excel
  4. nginx的代理服务
  5. php随机获取数组里面的值
  6. CodeForces - 841D Leha and another game about graph
  7. java高并发核心要点|系列2|锁的底层实现原理
  8. DeepFaceLab更新至2019.12.19
  9. 一、Linux 设备驱动介绍及开发环境搭建
  10. 【CF461B】Appleman and Tree