难度:中等
题目描述:
思路总结:一看到前K个,立即想到堆。
- 方法一:Counter和heapq的nlargest方法。
题解一:
from collections import Counter
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = Counter(nums)
return heapq.nlargest(k, count.keys(), key=count.get)
题解一结果: