※ 引述《Rushia (みけねこ的鼻屎)》之铭言:
: 692. Top K Frequent Words
: 给予一个字串阵列words和一个数字k,返回出现频率最高的k种字串行表,若多个字串
: 出现次数相同,则字母顺序较大的优先。
: Input: words = ["i","love","leetcode","i","love","coding"], k = 2
: Output: ["i","love"]
: Explanation:k为2而 "i" 和 "love" 是出现次数最多的字串。
这不就是 heapq.nlargest 吗
哈哈哈哈
哈哈哈哈哈哈哈
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
counts = Counter(words)
topk = heapq.nsmallest(k, list(counts.items()), key = lambda x:
(-x[1], x[0]))
return [word for word, count in topk]
因为要照 lexicographical order 所以用 nsmallest