python
哈希表+排序
import collections
class Solution:
def topKFrequent(self, words: List[str], k: int):
counter = collections.Counter(words)
res = []
counter = sorted(counter.items(), key=lambda kv:(-kv[1], kv[0]))
for i in range(k):
res.append(counter[i][0])
return res
堆排序
#
# return topK string
# @param strings string字符串一维数组 strings
# @param k int整型 the k
# @return string字符串二维数组
#
import collections
import heapq
class Words:
def __init__(self, fre, words):
self.fre = fre
self.words = words
def __gt__(self, other):
if self.fre > other.fre or (self.fre==other.fre and self.words < other.words):
return True
return False
class Solution:
def topKstrings(self , strings , k ):
# write code here
counter = collections.Counter(strings)
heap = []
res = []
for s, count in counter.items():
heapq.heappush(heap, Words(count, s))
if len(heap) > k:
heapq.heappop(heap)
for _ in range(k):
node = heapq.heappop(heap)
res.append([node.words, str(node.fre)])
return res[::-1]