Top K frequent elements


  • 0
    S
    from collections import Counter
    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            d = {}
            for i,v in dict(Counter(nums)).items():
                if v in d:
                    d[v].append(i)
                else:
                    d[v] = [i]
            
            res = []
            for i in range(k):
                m = max(d.keys())
                res += d[m]
                del d[m]
                if len(res) >= k:
                    break
            
            return res[:k]
    

Log in to reply
 

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