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

This commit is contained in:
Sangeeth Sudheer 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,21 @@
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
**Example 2:**
Input: nums = [1], k = 1
Output: [1]
**Constraints:**
* `1 <= nums.length <= 105`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.

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