Simple Solution Using Python 3


  • 0
    A
    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            d = {}
            for x in nums:
                if x in d:
                    d[x] += 1
                else:
                    d[x] = 1
            out = []
            util = []
            maxval = -1
            ele = None
            for x in d:
                util.append((x,d[x]))
            while k > 0:
                for x,y in util:
                    if y > maxval:
                        maxval = y
                        ele = x
                out.append(ele)
                removalbe = (ele,maxval)
                util.remove(removalbe)
                maxval = -1
                k -= 1
            return out
    
    

Log in to reply
 

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