Easy python solution using dictionary only

  • 1

    key is nums element,
    If we have key in dictionary, we increment the value by 1.

    class Solution(object):
    def topKFrequent(self, nums, k):
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        new_dict = dict()
        for item in nums:
            if not new_dict.has_key(item):
                new_dict[item] =1;
                new_dict[item] +=1;
        sorted_dict = sorted(new_dict, key=new_dict.get, reverse=True)
        return sorted_dict[:k]

  • 0

    Sorting is O(nlog(n)).
    Worst case of your code is O(n
    log(n)), when all elements are different.

Log in to reply

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