Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Input: nums = [1], k = 1
Output: [1]
Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2
Output: [1,2]
k is in the range [1, the number of unique elements in the array].Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
The most straightforward way to find the top k frequent elements is to count the frequency of each element using a hashmap, then sort the elements based on their frequency in descending order, and finally pick the first k elements from this sorted list.
k elements from the sorted list.nums.Instead of sorting all elements, we can use a Min-Heap (Priority Queue) to keep track of the top k elements. As we iterate through the hashmap, we maintain the size of the heap to be at most k by removing the smallest element whenever the size exceeds k.
k elements.k.nums.We can utilize a bucket sort technique since the maximum frequency of any element can't exceed the number of elements. We'll create an array of lists where each index corresponds to a frequency, then we'll fill each list with the numbers that have the respective frequency.
k frequent elements.nums. This is because we are only doing constant-time operations per element.