Top K Frequent Elements
You get an array of integers and a number k. Return the k numbers that appear most often, in any order; the answer is always unique. Our example: [9, 1, 9, 4, 1, 4, 1, 4] and k = 2 — the answer is [4, 1]: 4 and 1 appear 3 times each, 9 only twice.
- input
nums: integers, with repeats;k: how many numbers to return.- returns
- The
knumbers that appear innumsmost often, in any order. The answer is always unique. LeetCode wants it faster than O(n log n). - constraints
- 1 ≤ nums.length ≤ 10⁴
- −10⁴ ≤ nums[i] ≤ 10⁴
- 1 ≤ k ≤ the number of different numbers in nums
- the answer is unique
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
function topKFrequent(nums, k) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more heap and top k problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.