Example 1
- Input
- nums = [1, 1, 1, 2, 2, 3], k = 2
- Output
- [1, 2]
1 occurs three times and 2 occurs twice, making them the top 2 most frequent elements.
Given an integer array and a count k, return the k elements that appear most often. The answer is guaranteed unique and may be returned in any order.
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Counting frequencies is only half the job; the challenge is selecting the top k without paying a full sort. Because no value can occur more than n times, frequencies double as bucket indices for a linear-time selection. The answer is guaranteed unique as a set of k values; ties within that set are allowed.
Follow-up: use less than time, where n is the input length.
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <= number of distinct values in nums1 occurs three times and 2 occurs twice, making them the top 2 most frequent elements.
The only element present is automatically the most frequent.
Values 1 and 2 each occur four times, while 3 occurs twice. Both tied leaders belong in the answer; their order does not matter.
k equals the three distinct values, so all are returned despite different frequencies. Negative numbers and zero are ordinary map keys.
Rank distinct values by how often they appear, not by their numeric size. Example 1 has counts {1: 3, 2: 2, 3: 1}, so k = 2 selects 1 and 2. A frequency is never larger than the array length: place each value in the bucket numbered by its frequency, then visit buckets from high counts to low counts.
Reveal Count and Sort: intuition, complexity, and code
k cheaply.n, so index buckets by count and walk them from the top down.k equal to the number of distinct values returns every distinct value.n instead of n + 1, which overflows when one value fills the whole array.When the key range of a ranking is bounded by the input size, indexing buckets by rank selects the top entries in linear time.