CodingMedium
Top K Frequent Elements
You’re given an integer array nums and an integer k. Return the k values that appear most often in nums, in any order.
The answer is always unique, so there’s never a tie for the last of the k places. Aim for better than O(n log n) time.
Example 1
Input
nums = [4,4,4,6,6,9], k = 2Output[4,6]4 appears three times and 6 twice, more than any other value.
Example 2
Input
nums = [7], k = 1Output[7]Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
- 1 ≤ k ≤ the number of distinct values in nums
- The answer is unique