#K3361. Top K Frequent Elements
Top K Frequent Elements
Top K Frequent Elements
Given an integer array nums and an integer k, return the k most frequent elements. The answer should be printed in ascending order (to ensure consistency), separated by a space. Note that if k is 0, nothing should be printed.
Input/Output Method: The input is read from standard input (stdin) and the output should be printed to standard output (stdout).
The frequency ranking is based on the number of occurrences of each element in the array. In cases where frequencies are equal, any order is acceptable internally, but the final output should be sorted in ascending order.
Mathematically, if \( f(x) \) denotes the frequency of element \( x \) and the set of unique elements is \( U \), then you are required to select a subset \( S \subseteq U \) with \( |S| = k \) such that for every \( x \in S \) and \( y \notin S \), it holds that \( f(x) \ge f(y) \). Finally, output the sorted version of \( S \).
inputFormat
The input consists of three lines:
- The first line contains an integer n, representing the number of elements in the array.
- The second line contains n space-separated integers representing the array nums.
- The third line contains an integer k, the number of most frequent elements to output.
outputFormat
Print the k most frequent elements in ascending order, separated by a single space. If k is 0, output nothing.
## sample6
1 1 1 2 2 3
2
1 2