Top K Frequent Elements
Given an integer array nums and integer k, return the k most frequent elements as a list, in any order.
If several elements tie in frequency for the last of the k places, choose the one whose first occurrence in nums comes earliest.
The tests sort your list and print it space-separated (e.g. 1 2).
Example
1,1,1,2,2,3 2
1 2
- The inputs are
nums, here the six integers1,1,1,2,2,3, and , the number of elements to report. - The frequency of a value is how many positions of
numshold : , , . The three counts add up to , the length of the array. - Ranking the distinct values by frequency from highest to lowest gives ( times), then ( times), then ( time). The top are and ; the value is left out because two values already rank above it.
- The answer is the set , printed in ascending order as
1 2. Notice that only the distinct values matter in the output: no value is repeated, and the counts themselves are never shown. - Ties only matter at the cut-off: in with , both and appear twice, and wins because it shows up first, giving
1 4.
Constraints
- 1 <= len(nums) <= 10^5
- 1 <= k <= number of unique elements