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