python solution with explanation


  • 0
    Y
    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            bucket = [[] for i in range(len(nums) + 1)] # index is frequency, stores the nums in each freq
            frequency = {} #key: num, val: its frequency
            ans = []
            #count freq for each num
            for num in nums:
                if num not in frequency:
                    frequency[num] = 1
                else:
                    frequency[num] += 1
            #add num to bucket based on its freq
            for key in frequency.keys():
                bucket[frequency[key]].append(key)
            
            #reverse loop the bucket for the highest freqs
            for i in reversed(range(len(nums) + 1)):
                if k > 0 and len(bucket[i]) != 0:
                    ans.extend(bucket[i])
                    k -= len(bucket[i])
            return ans
    

Log in to reply
 

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