347.前k个高频元素-counter(leetcode)

给定一个非空的整数数组,返回其中出现频率前 高的元素。

 

 

法1)  使用 Counter 的most_common(k) 方法

from collections import Counter
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        counter_nums = Counter(nums)
        topK = counter_nums.most_common(k)
        res = [item[0] for item in topK]
        return res
 
还有常用的方法有:
  counter.update()   在原有的nums基础上,再加上一些new_nums  两个hash table做加法可查看 https://www.cnblogs.com/hycstar/p/9345751.html
  counter.sbstract()  在原有的nums上做减法 https://www.cnblogs.com/keke-xiaoxiami/p/8553076.html
  counter.elements()  列出nums https://www.cnblogs.com/keke-xiaoxiami/p/8553076.html
  
  counter.keys()
  counter.values()
  dict(counter) 
  list(counter) 与counter.elements()相似
 
法2) 官方答案 用 heap.nlargest()   回头再好好看看heap怎么用
  
class Solution:
    def topKFrequent(self, nums, k):

    count = collections.Counter(nums)
    return heap.nlargest(k,count.keys(),key = count.get())
  
  
  
posted @ 2020-03-21 18:03  ChevisZhang  阅读(146)  评论(0编辑  收藏  举报