feat(0347_top-k-frequent-elements): add py3 soln

This commit is contained in:
2022-04-09 23:15:20 +05:30
parent f2c76ac3f2
commit 569734d445
3 changed files with 47 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
# Time complexity: O(nlogn)
# https://github.com/python/cpython/blob/f52d987abfda25e50469c9b6fe1d19f72453d2de/Lib/collections/__init__.py#L608
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
return [val for val, _ in Counter(nums).most_common(k)]

View File

@@ -0,0 +1,19 @@
from heapq import heapify, heappop
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
c = Counter(nums)
# Python heapq creates a min-heap but we want a max-heap built
# against counts. Tuples are comparable in Python by default so
# we can create a tuple of (count, element) to build the heap. To
# mimic a max-heap, we can just negate the counts.
heap = [(-count, val) for val, count in c.items()]
heapify(heap)
result = [None] * k
for i, _ in enumerate(result):
result[i] = heappop(heap)[1]
return result