Given a non-empty array of integers, return the k most frequent elements.
For example,
Given[1,1,1,2,2,3]
and k = 2, return [1,2]
. Note:
-
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Top K 问题的变形,可以用collections.Count产生hash table。然后根据key值(freq)进行heap sort,这里可以仅仅维护一个size为 k 的 heap。
1 class Solution(object): 2 def topKFrequent(self, nums, k): 3 """ 4 :type nums: List[int] 5 :type k: int 6 :rtype: List[int] 7 """ 8 counts = collections.Counter(nums) 9 heap = []10 for key, cnt in counts.items():11 if len(heap) < k:12 heapq.heappush(heap, (cnt, key))13 else:14 if heap[0][0] < cnt:15 heapq.heapreplace(heap, (cnt, key))16 return [x[1] for x in heap]17