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]

  • 相关阅读:
    经验1
    Caffe和MatConvNet安装
    Matconvet的学习笔记
    CNN数据准备
    深度学习之卷积和池化
    深度学习之CNN的推导
    深度学习八(总结)
    深度学习七(卷积神经网络)
    深度学习六
    深度学习五
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10556834.html
Copyright © 2011-2022 走看看