π’ K Most Frequent Elements
Problem Statement:
Given an integer array nums and an integer k, return the k most frequent elements.
You may return the answer in any order.
Example
Input
nums = [1, 1, 1, 2, 2, 3]
k = 2
Output
[1, 2]
Explanation:
Element 1 appears 3 times, 2 appears 2 times, and 3 appears once.
The two most frequent elements are 1 and 2.
Constraints
- 1 β€
nums.length β€ 10β΅
- β10β΄ β€
nums[i] β€ 10β΄
- 1 β€
k β€ number of unique elements
Examples
Example 1
Input: [5, 2, 5, 3, 5, 3, 1, 1, 3], 2
Output: [5,3]
Example 2
Input: [7, 7, 7, 6, 6, 5, 5, 5, 5], 2
Output: [5,7]