feat(0347_top-k-frequent-elements): add py3 soln
This commit is contained in:
7
0347_top-k-frequent-elements/python3/smart.py
Normal file
7
0347_top-k-frequent-elements/python3/smart.py
Normal 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)]
|
||||
19
0347_top-k-frequent-elements/python3/solution.py
Normal file
19
0347_top-k-frequent-elements/python3/solution.py
Normal 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
|
||||
Reference in New Issue
Block a user