#C2475. K Most Frequent Elements
K Most Frequent Elements
K Most Frequent Elements
You are given T test cases. For each test case, you are provided with an integer N representing the size of an array, and another integer K which indicates the number of most frequent elements you need to output. Following this, an array of N integers is given.
Your task is to find the K most frequent elements in the array. The elements must be sorted primarily in descending order by their frequency. In the event of ties (elements with equal frequency), the element that appears earlier in the array should come first. If the number of distinct elements is less than K, output all unique elements.
Note: All formulas or mathematical expressions, if needed, should be written in LaTeX format. For example, the frequency order can be described as follows: $$\text{Sort by } f(x) \text{ in descending order, and by the first occurrence index in ascending order.}$$
inputFormat
The input is read from standard input (stdin) and has the following format:
T N K a1 a2 ... aN ... (repeated for each test case)
Where:
- T is the number of test cases.
- For each test case, the first line contains two integers N and K.
- The following line contains N space-separated integers.
outputFormat
For each test case, output a single line to standard output (stdout) containing the K most frequent elements separated by spaces. The order of the elements should be primarily by descending frequency, and if two elements have the same frequency, the one that appeared earlier in the input is printed first.
## sample1
8 2
1 1 1 2 2 3 3 3
1 3
</p>