Top K Frequent Elements

class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        """
        Counter is a subclass of dictionary
        Time Complexity:
        construct: O(n)
        the operator of most_common uses heapq to obtain top k value O(1)
        zip: O(n)
        """
        counter = collections.Counter(nums)
        res = list(zip(*counter.most_common(k)))[0]
        return list(res)

Last updated