Top K Frequent Elements
Medium
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]
Explanation
The frequencies are:
1 → 3 times
2 → 2 times
3 → 1 time
The two most frequent elements are 1 and 2.
Example 2
Input
nums = [1] k = 1
Output
[1]
Explanation
There is only one distinct element, so it is the most frequent element.
Constraints
1 <= nums.length <= 100000
1 <= k <= number of distinct elements in nums
-10000 <= nums[i] <= 10000
Hints:
Hint 1
Count the frequency of every element using a hash map.
Hint 2
Use a heap to keep track of the k elements with the highest frequencies.
Auto
Loading editor...
Input
Expected Output