Python easy-to-understand heap solution

  • 0

    from heapq import heappush, heappop

    def topKFrequent(self, nums, k):
        dic = {}
        for n in nums:
            dic[n] = dic.get(n, 0) + 1
        heap = []
        for key in dic.keys():
            heappush(heap, (dic[key], key))
        while len(heap) > k:  # pop out lease frequent elements
        res = []
        while heap:
        return res


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.