Gary Lai
  • Home
  • About
Sign in Subscribe

692. Top K Frequent Words

Last updated on  Mar 31, 2025

692. Top K Frequent Words

直接透過 Heap 的特性來完成。

class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        counter = Counter(words)
        q = []
        heapq.heapify(q)
        for key, value in counter.items():
            heapq.heappush(q, (-value, key))
        res = heapq.nsmallest(k, q)
        return [value for key, value in res]
Previous 271. Encode and Decode Strings
Next 1095. Find in Mountain Array
Gary Lai © 2025
  • Sign up
Powered by Ghost