classSolution: deftopKFrequent(self, words: List[str], k: int) -> List[str]: hash_map = dict() from heapq import heappush,heappushpop,heapify for e in words: if e in hash_map: hash_map[e] += 1 else: hash_map[e] = 1 # python的元组排序是按元素的字典序排序,因为数字要求从大到小,所以需要改为负数 ans = [(-v,k) for k,v in hash_map.items()] ans.sort() return [e[1] for e in ans][:k]
写法上还可以有点不一样,
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: deftopKFrequent(self, words: List[str], k: int) -> List[str]: hash_map = dict() from heapq import heappush,heappushpop,heapify for e in words: if e in hash_map: hash_map[e] += 1 else: hash_map[e] = 1 ans = sorted(hash_map.items(), key=lambda x: (-x[1],x[0]))[:k] return [e[0] for e in ans]
哈希表 + 优先队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: deftopKFrequent(self, words: List[str], k: int) -> List[str]: hash_map = dict() from heapq import heappush,heappushpop,heapify for e in words: hash_map[e] = hash_map.get(e, 0) + 1 h = [] for e in hash_map.keys(): heappush(h, (-hash_map[e], e)) ans = [] for _ inrange(k): ans.append(heapq.heappop(h)) # print('ans', ans) return [e[1] for e in ans]