Top K Frequent Elements
Top K Frequent Elements
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Function signature
func TopKFrequent(nums []int, k int) []int
Examples
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Explanation: 1 appears 3 times, 2 appears 2 times, 3 appears 1 time.
The two most frequent are 1 and 2.
Example 2:
Input: nums = [1], k = 1
Output: [1]
Example 3:
Input: nums = [4,4,4,4,3,3,2,1], k = 3
Output: [4,3,2]
Explanation: 4 (4 times), 3 (2 times), 2 (1 time) are the top 3.
Constraints
- 1 <= len(nums) <= 10000
- k is in the range [1, number of unique elements]
- The answer is guaranteed to be unique
Hints
- First count the frequency of each element using a hash map.
- Use a min-heap of size k. When the heap exceeds k elements, pop the minimum.
- What should you store in the heap? Think about what you're comparing.
Notes
- Time: O(n log k) using a heap, or O(n) using bucket sort.
- The heap approach generalizes well to streaming data.
Run tests to see results
No issues detected