leetcode347. 前 K 个高频元素

python自带的堆是小顶堆,所以可以根据元素的重复次数维护一个大小为k的小顶堆。
这样堆里的元素就是前k的高频元素了。

def topKFrequent(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: List[int]
    """
    dic = defaultdict(int)
    for num in nums:
        dic[num] += 1
    heap = []
    for num,count in dic.items():
        if len(heap) < k:
            heapq.heappush(heap,(count,num))
            continue
        if count > heap[0][0]:
            heapq.heappop(heap)
            heapq.heappush(heap,(count,num))
            
    return [heap[i][1] for i in range(len(heap)) ]

你可能感兴趣的:(hot100,python,算法,leetcode)