LeetCode: [692] 前K个高频单词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def topKFrequent(self, words, k):
words_dict = {}
for word in words:
if word not in words_dict.keys():
words_dict[word] = 1
else:
words_dict[word] += 1

words_dict = sorted(
words_dict.items(), key=lambda item: (-item[1], item[0]), reverse=True
)
# words_dict = sorted(words_dict.items(), key=lambda item: (-item[1], item[0], len(item[0])), reverse=True)
words_dict.reverse()
words_dict = words_dict[:k]
return [i[0] for i in words_dict]