Given a list of words and an integer k, return the top k frequent words in the list.
Given
[
"yes", "lint", "code",
"yes", "code", "baby",
"you", "baby", "chrome",
"safari", "lint", "code",
"body", "lint", "code"
]
for k = 3
, return ["code", "lint", "baby"]
.
for k = 4
, return ["code", "lint", "baby", "yes"]
,
You should order the words by the frequency of them in the return list, the most frequent one comes first. If two words has the same frequency, the one with lower alphabetical order come first.
这题是代码思路还是很明确的,先利用dict,统计每个字符出现的次数,之后进行排序,取前k个。但是注意提示中写的,两个单词出现频次相同时,按照词典序让比较小的排在前面。所以实际在写的时候,需要不仅靠频次排序,也需要靠词本身排序。代码如下:
class Solution: # @param {string[]} words a list of string # @param {int} k an integer # @return {string[]} a list of string def topKFrequentWords(self, words, k): map = {} for w in words: if w not in map: map[w] = 1 else: map[w] += 1 import heapq heap = [] for key, value in map.iteritems(): heapq.heappush(heap,(0-value,key)) res = [w[1] for w in heapq.nsmallest(k,heap,key = lambda x: (x[0],x[1]))] return res
时间: 2024-10-05 16:26:04