Problem
Given a non-empty array of integers, return the k most frequent elements.
Example
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Input: nums = [1], k = 1
Output: [1]
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.
# solution1
from collections import defaultdict,Counter
class Solution(object):
def topKFrequent(self, nums, k):
# 使用collection库中的Counter构造一个dict,统计每个值出现的次数
frq = defaultdict(list)
for key, cnt in Counter(nums).items():
frq[cnt].append(key)
# 遍历取出频率最高的k个数放入数组,不用再排序
res = []
for times in reversed(range(len(nums) + 1)):
res.extend(frq[times])
if len(res) >= k: return res[:k]
return res[:k]
# 讨论区里的一行方案,不过面试肯定不能这么干哈
class Solution(object):
def topKFrequent(self, nums, k):
return zip(*collections.Counter(nums).most_common(k))[0]