diff --git a/0347_top-k-frequent-elements/README.md b/0347_top-k-frequent-elements/README.md new file mode 100644 index 0000000..ce10dc7 --- /dev/null +++ b/0347_top-k-frequent-elements/README.md @@ -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. \ No newline at end of file diff --git a/0347_top-k-frequent-elements/python3/smart.py b/0347_top-k-frequent-elements/python3/smart.py new file mode 100644 index 0000000..d5c6d30 --- /dev/null +++ b/0347_top-k-frequent-elements/python3/smart.py @@ -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)] diff --git a/0347_top-k-frequent-elements/python3/solution.py b/0347_top-k-frequent-elements/python3/solution.py new file mode 100644 index 0000000..edb66e2 --- /dev/null +++ b/0347_top-k-frequent-elements/python3/solution.py @@ -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