You get an integer array nums and an integer k. Some values in nums repeat. Return the k values that appear most often.
The inputs are chosen so that the answer is never in doubt: the k-th most common value always appears strictly more often than any value left out. You may return the k values in any order.
7 appears three times, 3 twice and 5 once, so the two most common values are 7 and 3. [3,7] is just as correct.
-1 appears four times, more than 5 (three times) or 2 (once).
When k equals the number of different values, every value is in the answer.
Constraints
1 <= nums.length <= 10⁵-10⁴ <= nums[i] <= 10⁴1 <= k <= the number of different values in numsk is less than the number of different values, the k-th highest count is greater than the (k+1)-th.First count how often each value appears, using a hash map. The question is then just which k counts are largest.
The problem is two questions in a row. How often does each value appear? Then, which k of those counts are the biggest?
Time O(n)Space O(n)
The full walkthrough and code are part of Premium