import heapq
from collections import Counter
class Solution1:
def topKFrequent(self, words: list[str], k: int) -> list[str]:
c = Counter(words)
return [x for x in sorted(c, key=lambda key: (-c[key], key))][:k]
class Solution:
def topKFrequent(self, words: list[str], k: int) -> list[str]:
c = Counter(words)
return heapq.nsmallest(k, c, key=lambda key: (-c[key], key))
2 posts tagged with "Heap (Priority Queue)"
View All Tags1046. Last Stone Weight
import heapq
class Solution:
def lastStoneWeight(self, stones: list[int]) -> int:
stones.append(0)
stones = list(map(lambda x: -x, stones))
heapq.heapify(stones)
while len(stones) > 1:
y, x = -heapq.heappop(stones), -heapq.heappop(stones)
if x != y:
heapq.heappush(stones, -(y - x))
return -heapq.heappop(stones)