数据结构之leetcode 347题

1 347题目描述

给出一个列表,输出前k个频率最高的元素。

2 源代码

# 347题
# 我的解答
def topKFrequent(nums, k):
    m = {}
    num = []
    for i in nums:
        if i not in m:
            m[i] = 1
        else:
            m[i] += 1
    
    for key, v in m.items():
        p = (v, key)
        num.append(p)
    
    num.sort(key=lambda x: x[0], reverse=True)
    
    print(num)
    ans = []
    for i in range(k):
        ans.append(num[i][1])
#         print(ans, i)
        
    return ans
    
# 347题
# 大佬(柳婼)简洁解答(时间:O(NlogN),空间:O(N))
def topKFrequent(nums, k):
    freq_dict = {}
    for v in nums:
        freq_dict[v] = freq_dict.get(v, 0) + 1
    res = list(freq_dict.items())
    res.sort(key=lambda x: x[1], reverse=True)
    return [res[i][0] for i in range(k)]
    
# 347题
# 超级大佬(薛玉洁)简洁解答(用堆,时间:O(N),空间:O(1))

def topKFrequent(nums, k):
    import heapq
    # 先利用字典计数
    fre_dict = {}
    for v in nums:
        fre_dict[v] = fre_dict.get(v, 0) + 1
    
    # 创建最小堆
    heap = []
    for key, value in fre_dict.items():
        if len(heap) < k:
            heapq.heappush(heap, (value, key))
            continue
        if value > heap[0][0]:
            heapq.heapreplace(heap, (value, key))
            
    res = []
    while heap:
        res.insert(0, heapq.heappop(heap)[1])
        
    return res
    
topKFrequent([3,0,1,0], 1)  

输出

[0]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值