Very simple accepted python solution utilizing built-ins


  • 0
    E

    This is dead-drop simple, but uses built-in sugar.

    class Solution(object):
        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            hash_table = {}
            for num in nums:
                if not num in hash_table:
                    hash_table[num] = 0
                hash_table[num] += 1
            
            frequencies = sorted(list(hash_table.items()), key=lambda x: x[1], reverse=True)
            
            return [x[0] for x in frequencies[:k]]
    

  • 1
    F

    @echoloth :

    Looks like we had the same idea! My code is below

        def topKFrequent(self, nums, k):
            freq={}
            for i in nums:
                if not i in freq:
                    freq[i] = 1
                else:
                    freq[i] += 1
      
            sorted_x = sorted(freq, key=freq.get, reverse=True)
            return sorted_x[:k]

Log in to reply
 

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