#C4658. Find Frequent Elements
Find Frequent Elements
Find 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 two or more elements have the same frequency, the element with the larger value should appear first in the output.
You are guaranteed that \(k\) does not exceed the number of unique elements in the array.
Constraints:
- \(1 \leq n \leq 10^5\), where \(n\) is the number of elements in the array.
- \(-10^4 \leq nums[i] \leq 10^4\) for each element \(nums[i]\) of the array.
- \(1 \leq k \leq n\)
inputFormat
The input is read from stdin and consists of two lines. The first line 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 be output. The second line contains (n) space-separated integers representing the array.
outputFormat
Print a single line to stdout containing (k) integers separated by a single space: the (k) most frequent elements sorted primarily by frequency (in descending order) and secondarily by numerical value (in descending order if frequencies are equal).## sample
6 2
1 1 1 2 2 3
1 2