LeetCode: LeetCode official website - a technology growth platform loved by global geeks
Given a list of words words
and an integer k
, return the previous k
word with the most occurrences.
The returned answers should be sorted by word frequency from most to least. If different words have the same frequency, sort them lexicographically .
Example 1:
Input: words = ["i", "love", "leetcode", "i", "love", "coding"], k = 2 Output: ["i", "love"] Parsing: " i " and "love" is the two most frequently occurring words, both 2 times. Note that "i" comes before "love" in alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 Output : [ "the", "is", "sunny", "day"] Parsing: "the", "is", "sunny" and "day" are the four words with the most occurrences, and the occurrences are 4, 3, 2 and 1 time.
Notice:
1 <= words.length <= 500
1 <= words[i] <= 10
words[i]
Consists of lowercase English letters.k
The range of values is[1, 不同 words[i] 的数量]
Sample code 1:
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
hash = collections.Counter(words)
res = sorted(hash, key=lambda word: (-hash[word], word))
return res[:k]
Sample code 2:
from heapq import nsmallest
from typing import List
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return nsmallest(k, freq, key=lambda x: (-freq[x], x))
if __name__ == '__main__':
words = ["i", "love", "leetcode", "i", "love", "coding"]
obj = Solution()
res = obj.topKFrequent(words, 2)
print(res)