Python Easy solution, beats 100%


  • 0
    T

    Here's a solution that makes a dictionary where the key is the element and the value is the number of times it appears. Then I creates a sorted list of tuples out of the dictionary and return the elements up to k.

        def topKFrequent(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            freq = {}
            for num in nums:
                if num in freq:
                    freq[num]+=1
                else:
                    freq[num]=0
                    
            freq = sorted(freq, key=freq.get, reverse=True)
            return freq[:k]
    

  • 0
    A

    But doesnt the sorting make it O(n logn)? The question says you must do it better than that...


  • 1
    H

    @adarshmurthy i think it is better than O(nlogn),because the size of the dict is smaller than n, so the complexity to sort the dict can be smaller than O(nlogn)


Log in to reply
 

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