#C14705. K Most Frequent Elements

    ID: 44384 Type: Default 1000ms 256MiB

K Most Frequent Elements

K Most Frequent Elements

You are given an array of integers and an integer k. Your task is to find the k most frequent elements in the array.

In more formal terms, given an array nums of length N and an integer k, you need to compute the frequency of each element. Then, among all distinct numbers, select the k numbers with the highest frequencies. If there is a tie at the k-th frequency, choose the number with the smallest value.

The answer should be output in ascending order.

The frequency ordering can be formalized as follows: for any two distinct numbers x and y, x comes before y if either:

  • \(f(x) > f(y)\), where \(f(x)\) is the number of occurrences of x, or
  • \(f(x) = f(y)\) and \(x < y\).

After selecting the top k elements based on the above rules, output them in ascending order.

inputFormat

The input is read from stdin and consists of two lines:

  1. The first line contains two integers N and k, where N is the number of elements in the array.
  2. The second line contains N integers separated by spaces. If N is 0, the second line will be empty.

outputFormat

Print the k most frequent elements in the array in ascending order, separated by a single space. Output is written to stdout.

## sample
7 2
4 1 -1 2 -1 2 3
-1 2