347. 前 K 个高频元素 大根堆

题意:返回的是高频元素的值 nums = [1,1,1,2,2,3], k = 2输出[1,2],1,2这两个元素频率最高
前k个大的小的,第k个大的小的 ,都用大根堆小根堆来做。相对于排序,时间复杂度更低
利用heapq小根堆的包

import heapq
class Solution:
    def topKFrequent(self,nums,k):
        heap_max=[]
        result=[]
        dic = collections.defaultdict(int)
        for num in nums:
            dic[num] +=1
        for i in dic: #i 是字典的key
            heapq.heappush(heap_max,(-dic[i],i))#小根堆作为大根堆,其实仍是小根堆,只不过最小值的相反数是最大值
        for j in range(k):
            result.append(heapq.heappop(heap_max)[-1])
        return result

collections.Counter()
a = [1,1,3,4,3] b=Counter(a) b={1:2,3:2,4:1} key是a的值, value是统计次数
返回前k个元素,这时候可以应用Counter的一个函数,most_common(k),但是返回的形式是一个元祖列表,类似[(1,2),(3,2),(4,1)]的形式

from collections import Counter
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        return [i[0] for i in Counter(nums).most_common(k)]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值