Given an integer array
nums and an integer
k, return the
k most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Explanation: The element
1 appears 3 times and
2 appears 2 times, making them the two most frequent elements.
Example 2:
Input: nums = [1], k = 1
Output: [1]
Explanation: Since there is only one element in the array, it becomes the most frequent element automatically.
Example 3:
Input: nums = [4,4,4,6,6,1,1,1,1], k = 2
Output: [1,4]
Explanation: The element
1 appears 4 times and
4 appears 3 times, so they are the top 2 frequent elements.