Return the values that appear most frequently in an integer array.
Given an integer array nums and an integer k, return the k elements that occur most often in nums.
The answer can be returned in any order.
This problem focuses on identifying the most frequent values efficiently rather than fully sorting the array by frequency.
numskk distinct values from numsk is valid and does not exceed the number of distinct elements.nums: integer arrayk: integerReturn the k most frequent distinct elements.
k1 <= k <= number of distinct values in numsnums contains at least one elementExample 1
Input
nums = [1,1,1,2,2,3], k = 2
Output
[1,2]
Explanation
The frequencies are: 1 -> 3, 2 -> 2, 3 -> 1. The two most frequent elements are 1 and 2.
Example 2
Input
nums = [4,4,4,6,6,1], k = 1
Output
[4]
Explanation
The element 4 appears three times, which is more than any other value.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.