Top K Frequent Elements
Part of Practice: Hash Keys & Buckets
Given an integer array nums and an integer k, return the k values that occur most often. The answer is guaranteed to be unique (no ties that would make the choice ambiguous), and you can return the values in any order.
The array can hold up to 100,000 numbers, and the follow-up asks for something better than sorting all the frequencies, i.e. better than O(n log n).
Examples
- Input:
- nums = [1, 1, 1, 2, 2, 3], k = 2
- Output:
- [1, 2]
1 appears 3 times and 2 appears twice; 3 appears only once and is left out.
- Input:
- nums = [1], k = 1
- Output:
- [1]
- Input:
- nums = [4, 4, 4, 5, 5, 6], k = 1
- Output:
- [4]
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.