1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if k == len((nums)): return nums # 1. build hash map : character and how often it appears # O(N) time count = Counter(nums) # 2-3. build heap of top k frequent elements and # convert it into an output array # O(N log k) time return heapq.nlargest(k, count.keys(), key=count.get)