zoukankan      html  css  js  c++  java
  • 栈和队列_leetcode347(优先队列)

    class Solution1(object):
    def topKFrequent(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: List[int]
    """
    Dict = {}
    for i in range(len(nums)):
    if nums[i] in Dict:
    Dict[nums[i]] = Dict[nums[i]] + 1
    else:
    Dict[nums[i]] = 1

    output = sorted(Dict.items(), key=lambda e: e[1], reverse=True)

    final = []
    for i in range(k):
    final.append(output[i][0])
    return final




    class Solution:
    def topKFrequent(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: List[int]
    """
    from queue import PriorityQueue

    count_list = dict()
    for i in nums:
    count_list[i] = count_list.get(i, 0) + 1

    p = PriorityQueue()
    for i in count_list.items():
    if p.qsize() == k:
    # 判断优先队列长度是否满足k
    if i[1] > p[0]: #bug
    p.get()
    p.put((i[1], i[0]))# 通过 (频率,元素) 形式存储
    else:
    p.put((i[1], i[0]))

    result = list()
    while not p.empty():
    _, v = p.get()
    result.append(v)
    return result



    class Solution:
    def topKFrequent(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: List[int]
    """
    import heapq
    count_list = dict()

    for i in nums:
    count_list[i] = count_list.get(i, 0) + 1

    p = list()

    for i in count_list.items():
    if len(p) == k:
    if i[1] > p[0][0]:
    heapq.heappop(p)
    heapq.heappush(p, (i[1], i[0]))
    else:
    heapq.heappush(p, (i[1], i[0]))

    return [i[1] for i in p]

  • 相关阅读:
    迭代器、生成器、装饰器(转)
    Python小数据池
    接阿里云oss有感
    VSCode快捷键
    前端跨域调请求 nginx反向代理
    Git生成密钥
    【westorm系列之二】配置格式化
    钉钉安卓端无法渲染数据
    express 写接口
    js正则匹配身份证号 有坑
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10556834.html
Copyright © 2011-2022 走看看