#K6356. K Most Frequent Elements
K Most Frequent Elements
K Most Frequent Elements
You are given an array \(A\) of \(N\) integers and an integer \(k\). Your task is to find the \(k\) most frequent elements in the array.
If two or more elements have the same frequency, they should be sorted in ascending order.
Note: The answer should be printed in a single line with the \(k\) integers separated by a single space.
Examples:
- For \(A = [1, 1, 1, 2, 2, 3]\) and \(k = 2\), the output is
1 2
. - For \(A = [4, 4, 4, 2, 2, 3, 3, 3]\) and \(k = 2\), the output is
3 4
.
Consider using the formula for frequency count where \(freq(x)\) represents the frequency of an element \(x\). Then, sort the elements primarily by \(-freq(x)\) and secondarily by \(x\) in ascending order, and finally pick the top \(k\) elements.
inputFormat
The input is given in two lines:
- The first line contains two integers \(N\) and \(k\), where \(N\) is the number of elements in the array and \(k\) is the number of most frequent elements to output.
- The second line contains \(N\) space-separated integers representing the array \(A\).
outputFormat
Output a single line with \(k\) integers, which are the \(k\) most frequent elements in the array. The numbers should be separated by a single space.
## sample6 2
1 1 1 2 2 3
1 2