Description

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Examples

Input:nums = [1,1,1,2,2,3], k = 2
Output:[1,2]
Explanation:

1 appears 3 times, 2 appears 2 times.

Input:nums = [1], k = 1
Output:[1]
Explanation:

Only one element.

Input:nums = [4,1,-1,2,-1,2,3], k = 3
Output:[-1,2,4] or [-1,2,1] or [-1,2,3] or [2,-1,4] or [2,-1,1] or [2,-1,3]
Explanation:

-1 appears 2 times, 2 appears 2 times, and 4, 1, 3 each appear 1 time. Since the requirement is k=3 elements and there's a tie for third place, any combination of the two most frequent elements (-1 and 2) plus any one of the elements that appear once is valid.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!