Given an integer array nums and an integer k, return the k most frequent elements, in any order. The answer is guaranteed to be unique.
A frequency is at most n, so drop each value into bucket[frequency]. Walk the buckets from the highest frequency down until k values are collected.
1function topKFrequent(nums: number[], k: number): number[] {2const count = new Map<number, number>();3for (const x of nums) count.set(x, (count.get(x) ?? 0) + 1);4const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => []);5for (const [x, c] of count) buckets[c].push(x);6const res: number[] = [];7for (let f = nums.length; f > 0 && res.length < k; f--)8for (const x of buckets[f]) if (res.length < k) res.push(x);9return res;10}
Count every value.
Space: play/pause · ←/→: step