#K53417. Top K Frequent Elements
Top K Frequent Elements
Top K Frequent Elements
Given an array of integers and an integer , your task is to find the most frequent elements in the array. The output should list these elements in order of descending frequency. In the event of a tie (i.e. two numbers have the same frequency), the number with the smaller value should come first.
For example, consider the array [1, 1, 1, 2, 2, 3] with . The frequency of 1 is 3, 2 is 2, and 3 is 1. Therefore, the answer is: 1 2.
Note: You must read the input from standard input (stdin) and write the output to standard output (stdout).
inputFormat
The input is given via standard input and consists of three lines:
- The first line contains an integer , the number of elements in the array.
- The second line contains space-separated integers representing the array.
- The third line contains an integer , representing the number of top frequent elements to output.
outputFormat
Output the most frequent elements separated by a single space. The elements should be ordered by descending frequency. If two elements have the same frequency, output the smaller element first.## sample
6
1 1 1 2 2 3
2
1 2