Python solution : Using Heap


  • 0
    S
    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            d = {}
            h = []
            ans = []
            for i in nums:
                d[i] = d.get(i,0) + 1
            for num, value in d.iteritems():
                heapq.heappush(h,(num,value))
            for i in heapq.nlargest(k, h, key = lambda e:e[1]):
                ans.append(i[0])
            return ans
    

Log in to reply
 

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