Top K Frequent Elements
Problem statement
Given a nonempty integer array nums and an integer k, return the k distinct values that appear most often.
Return values in decreasing frequency order. When frequencies are equal, put the smaller numeric value first. This tie rule determines both membership at the cutoff and output order.
Function
topKFrequent(nums: int[], k: int) → int[]Examples
Example 1
nums = [1,1,1,2,2,3]k = 2return = [1,2]The counts of 1, 2 and 3 are three, two and one.
Example 2
nums = [4,4,-1,-1,7]k = 1return = [-1]Both -1 and 4 occur twice; the smaller value wins the cutoff tie.
Example 3
nums = [3,1,2]k = 3return = [1,2,3]All counts are one, so numeric ascending order decides the result.
Constraints
1 <= nums.length <= 100000.- Every value is a signed 32-bit integer.
1 <= k <=the number of distinct input values.