Python easy-to-understand heap solution


  • 0
    Y

    '''
    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
            heappop(heap)
            
        res = []
        while heap:
            res.append(heappop(heap)[1])
        return res
    

    '''


Log in to reply
 

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