Problem · Array
Top K Frequent Elements
Learn this problemProblem statement
You are given an integer array nums and an integer k. Return the k distinct values that occur most frequently.
The selected set is guaranteed to be unique. For deterministic output, list selected values by decreasing frequency; when two selected values have the same frequency, list the smaller value first.
Function
topKFrequent(nums: int[], k: int) → int[]Examples
Example 1
nums = [1,1,1,2,2,3]k = 2return = [1,2]The frequencies are three for 1, two for 2, and one for 3.
Example 2
nums = [4,4,-1,-1,2]k = 2return = [-1,4]Both selected values occur twice, so the smaller value comes first.
Constraints
1 <= nums.length <= 100000-10000 <= nums[i] <= 100001 <= k <=the number of distinct values innums.- The set of
kmost frequent values is unique.