题目
Given a non-empty array of integers, return the k most frequent elements.
解题思路
首先将数组转换成一个Counter,然后使用优先队列找到出现次数最多的k个元素
代码
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
q = []
for num, freq in Counter(nums).items():
if len(q) == k:
heappushpop(q, (freq, num))
else:
heappush(q, (freq, num))
return [x[1] for x in q]
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
ct = Counter(nums)
return heapq.nlargest(k, ct.keys(), key=ct.get)