#K84332. Most Frequent Elements
Most Frequent Elements
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 case of a tie in frequency, the elements should be ordered according to the order in which they first appear in the array.
Formally, given an array ( A[0 \ldots n-1] ) and an integer ( k ), let ( f(x) ) be the frequency of element ( x ) in ( A ) and ( first(x) ) be the first index at which ( x ) appears. You need to output the ( k ) elements sorted primarily by descending frequency ( (f(x)) ) and secondarily by ascending first occurrence ( (first(x)) ).
inputFormat
The input is read from standard input (stdin). The first line contains two integers ( n ) and ( k ), where ( n ) is the number of elements in the array. If ( n > 0 ), the second line contains ( n ) integers separated by spaces representing the elements of the array. If ( n = 0 ), the second line is omitted.
outputFormat
Output the ( k ) most frequent elements in one line, separated by a space. If the resulting list is empty, output an empty line.## sample
6 2
1 1 1 2 2 3
1 2
</p>