#K72072. Top K Frequent Elements
Top K Frequent Elements
Top K Frequent Elements
You are given an array of integers and an integer \(k\). Your task is to determine the \(k\) most frequent elements in the array. The result should be displayed in descending order of frequency. In case of a tie (i.e., when two elements have the same frequency), the elements should be output in the order of their first appearance in the array.
Example:
Input: [1, 1, 1, 2, 2, 3], k = 2 Output: 1 2
Note that the input is provided via standard input (stdin) and the output should be printed to standard output (stdout).
inputFormat
The input is read from standard input and consists of two lines:
- The first line contains two integers \(n\) and \(k\), where \(n\) is the number of elements in the array, and \(k\) specifies how many top frequent elements need to be returned.
- The second line contains \(n\) space-separated integers representing the array.
outputFormat
Print the \(k\) most frequent elements in descending order of frequency, separated by a single space. If multiple elements have the same frequency, they should appear in the order of their first occurrence.
## sample6 2
1 1 1 2 2 3
1 2
</p>