#K6021. k Most Frequent Elements
k Most Frequent Elements
k Most Frequent Elements
You are given an array of integers and an integer k. Your task is to determine the k most frequent elements in the array. The result should be ordered by decreasing frequency; if two elements have the same frequency, the smaller element should come first.
More formally, let the frequency of an element be defined as the number of times it appears in the input array. Return the top k elements sorted primarily by their frequency (in descending order) and secondarily by their numerical value (in ascending order).
Example: For an input array of [1, 1, 1, 2, 2, 3] with k = 2, the answer is [1, 2] because 1 appears three times, 2 appears two times, and 3 appears once.
inputFormat
The first line of input contains two integers n and k, where n is the number of elements in the array, and k is the number of most frequent elements to output. The second line contains n space-separated integers representing the elements of the array.
outputFormat
Output the k most frequent elements separated by a space, ordered first by decreasing frequency and then by increasing numerical value if frequencies are the same.
## sample6 2
1 1 1 2 2 3
1 2