Top K Frequent Elements
- Array
- Hash Map
- Bucket Sort
- Heap
Given an integer array nums and an integer k, return the k most frequent values.
Order the result by descending frequency. When two values have the same frequency, place the smaller numeric value first.
Different frequency levels
- Input
"k": 2, "nums": [8, 8, 8, -2, -2, 5, 5, 5, 5, 13]
- Output
[5, 8]
Explanation: The value 5 occurs four times and 8 occurs three times.
Tie resolved numerically
- Input
"k": 3, "nums": [42, 42, 7, 7, -3, -3, 11]
- Output
[-3, 7, 42]
Explanation: The three selected values tie at two occurrences, so numeric order decides their positions.
Constraints
- 1 <= nums.length <= 100,000
- 1 <= k <= the number of distinct values
- The answer is defined by the deterministic ordering above
Follow-up
Can you solve the problem faster than O(n log n)?