← All problemsExample 1 Example 2
Problem
Top K Frequent Elements
Medium- arrays
- hash-table
- heap
Count how often each value occurs in nums, and return the k values with the highest counts. The order of the values in the result does not matter.
- Input
nums = [4, 4, 7, 9, 9, 9, 4, 9, 2], k = 2- Output
[9, 4]- Explanation
9occurs four times,4three times, and7and2once each, so9and4are the top two. Any order is accepted, so[4, 9]is also correct.
- Input
nums = [2, 6, 9, 6, 2], k = 3- Output
[2, 6, 9]- Explanation
kequals the number of distinct values, so every value is returned.
Constraints:
1 <= nums.length <= 10^5kis always valid:1 <= k <= d, wheredis the number of distinct values innums
Follow-up: sorting all the distinct values by count is a valid answer. Can you do better when k is much smaller than d?
Tab indents. Press Esc, then Tab to leave the editor.
Ctrl or ⌘ + Enter runs the tests.
Run your code to see every test here. Nothing is submitted or recorded.