#C13664. K Frequent Elements
K Frequent Elements
K Frequent Elements
You are given a list of integers and an integer \(k\). Your task is to find the \(k\) most frequent elements in the list.
The elements should be sorted primarily by their frequency in descending order, and if two elements have the same frequency, they should be sorted by their value in ascending order.
If \(k\) is larger than the number of unique elements, output all unique elements. If the list is empty, output an empty line.
Example: For the input list: [1, 1, 2, 2, 2, 3] with \(k = 2\), the output should be: [2, 1].
inputFormat
The input is provided through standard input (stdin) in the following format:
- The first line contains an integer \(n\), representing the number of elements in the list.
- The second line contains \(n\) space-separated integers.
- The third line contains an integer \(k\), indicating how many frequent elements to output.
outputFormat
Output the \(k\) most frequent elements in one line, separated by a single space. The ordering should be based on frequency (in descending order) and by value (in ascending order) in case of ties.
## sample6
1 1 2 2 2 3
2
2 1
</p>