Arrays and Hashing Counting and voting
67. Top K Frequent Elements
You are given an array of integers nums and an integer k. Return the k different values that appear in
nums most often.
The answer is always unique: the input never has a tie for the last place in the answer. You may return the values in any order. The examples list them from smallest to largest.
Example 1
Input: nums = [4, 1, -2, 4, 1, 4, 7, 1, 4], k = 2
[1,4]Explanation: 4 appears four times and 1 appears three times. -2 and 7 appear once each, so they are not in
the answer.
Example 2
Input: nums = [-5, -5, 3, -5, 3, 0], k = 3
[-5,0,3]Explanation: There are exactly three different values, so all of them are in the answer. Negative values and zero count like any other value.
Example 3
Input: nums = [1000000000, 1000000000, 1000000000, 1000000000]
k = 1
[1000000000]Explanation: Every element is the same value, which appears nums.length times.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1091 ≤ k ≤the number of different values innums- The
k-th most frequent value appears more often than every value outside the answer.
Clarifying questions
What you would ask an interviewer before writing any code.