比较显然的就是用defaultdict或者直接用Count数一下排个序然后把相应的数据输出即可,这个算法的时间复杂度是O(NlogN),空间复杂度是O(N)。然后第K大问题总是会有堆,鉴于很久没复习了我先复制粘贴在这里。
from collections import Counter
class Solution:
def topKFrequent1(self, words: List[str], k: int) -> List[str]:
cnt = Counter(words)
res = sorted(cnt.items(), key=lambda x: (-x[1], x[0]))
return [x[0] for x in res[:k]]
def topKFrequent2(self, words, k):
count = collections.Counter(words)
heap = [(-freq, word) for word, freq in count.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in xrange(k)]
PREVIOUSlc1249.移除无效的括号
NEXTmq029.合并两个有序链表