Top K Frequent Numbers
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write topKFrequent(nums, k): the k numbers that appear most often in nums, most frequent first. When two appear equally often, the smaller number comes first, and if there are fewer than k different numbers, return them all. topKFrequent([1, 1, 1, 2, 2, 3], 2) gives [1, 2]. The checks include 100,000 numbers, so count each number once rather than counting again for every one.
Your code must pass
- Returns the most frequent numbers first
- Breaks ties by the smaller number
- Returns every number when there are fewer than k
- Is fast enough for 100,000 numbers