Re: [闲聊] 每日LeetCode

楼主: pandix (面包屌)   2022-10-19 19:07:59
※ 引述《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
作者: sixB (6B)   2022-10-19 19:21:00
怎么都记得起来什么题是什么==
作者: Rushia (みけねこ的鼻屎)   2022-10-19 19:21:00
我要鲨了你

Links booklink

Contact Us: admin [ a t ] ucptt.com