Last active
August 20, 2022 20:06
-
-
Save mdpabel/c81205ff0e3fcffc39cf2305ee6b9737 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import Counter | |
from heapq import heappush, heappop, heappushpop | |
class Item(object): | |
def __init__(self, word, freq): | |
self.word = word | |
self.freq = freq | |
def __lt__(self, other): | |
if self.freq == other.freq: | |
return self.word > other.word # lower alpha order | |
return self.freq < other.freq # higher freq | |
class Solution: | |
def topKFrequent(self, words: List[str], k: int) -> List[str]: | |
c = Counter(words) | |
heap = [] | |
heapify(heap) | |
for key in c: | |
item = Item(key, c[key]) | |
if len(heap) < k: | |
heappush(heap, item) | |
elif item > heap[0]: | |
heappop(heap) | |
heappush(heap, item) | |
res = [] | |
for _ in range(k): | |
res.append(heappop(heap).word) | |
return res[::-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment