Top K Frequent Elements
Given an integer array and an integer k, return the k most frequent elements. You may return the answer in any order.
Write a function that returns the k most frequent elements from an array. If there are multiple answers, return any of them.
How to Solve
First, count the frequency of each element using a hash map. Then, use a min-heap (priority queue) of size k to keep track of the top k elements, or sort the entries by frequency and take the top k. Alternatively, use bucket sort for O(n) solution.
Click to reveal
Example 1:
Input:
nums = [1,1,1,2,2,3]
k = 2
Output: [1,2]
Example 2:
Input:
nums = [1]
k = 1
Output: [1]
Example 3:
Input:
nums = [4,1,-1,2,-1,2,3]
k = 2
Output: [-1,2]