#K53417. Top K Frequent Elements

    ID: 29527 Type: Default 1000ms 256MiB

Top K Frequent Elements

Top K Frequent Elements

Given an array of integers and an integer kk, your task is to find the kk 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 k=2k=2. 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:

  1. The first line contains an integer nn, the number of elements in the array.
  2. The second line contains nn space-separated integers representing the array.
  3. The third line contains an integer kk, representing the number of top frequent elements to output.

outputFormat

Output the kk 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