Python Easy solution, beats 100%

  • 0

    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 = sorted(freq, key=freq.get, reverse=True)
            return freq[:k]

  • 0

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

  • 1

    @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.