huimeich / leetcode-solution

0 stars 0 forks source link

692. Top K Frequent Words #267

Open huimeich opened 4 years ago

huimeich commented 4 years ago

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

huimeich commented 4 years ago
def topKFrequent(self, words: List[str], k: int) -> List[str]:
    count = collections.Counter(words)
    candidates = list(count.keys())
    candidates.sort(key = lambda w: (-count[w], w))
    return candidates[:k]
huimeich commented 4 years ago
def topKFrequent(self, words: List[str], k: int) -> List[str]:
    count = collections.Counter(words)
    heap = [(-freq, word) for word, freq in count.items()]
    heapq.heapify(heap)
    return [heapq.heappop(heap)[1] for _ in range(k)]