Leetcode 347 Top K Frequent Elements
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.
第一想法自然是放hash里面统计出现次数然后根据次数排序后取出前k个key
import operator class Solution(object): def topKFrequent(self, nums, k): h = {} for x in nums: if h.has_key(x): h[x] += 1 else: h[x] = 1 sorted_h = sorted(h.items(), key=operator.itemgetter(1)) sorted_h.reverse() return [x for (x,y) in sorted_h[:k]]