Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static List<int> find_top_k_frequent_elements(List<int> arr, int k) {
- List<int> Output = new List<int>();
- Dictionary<int,int> numsList = new Dictionary<int,int>();
- foreach(int ele in arr){
- if(numsList.ContainsKey(ele))
- numsList[ele] += 1;
- else
- numsList.Add(ele,1);
- }
- Dictionary<int,List<int>> dictFreq = new Dictionary<int,List<int>>();
- int highestFreq = 0;
- foreach(KeyValuePair<int, int> kvp in numsList){
- highestFreq = Math.Max(highestFreq, kvp.Value);
- if(dictFreq.ContainsKey(kvp.Value)){
- List<int> numbers = dictFreq[kvp.Value];
- numbers.Add(kvp.Key);
- }
- else{
- List<int> numbers = new List<int>();
- numbers.Add(kvp.Key);
- dictFreq.Add(kvp.Value, numbers);
- }
- }
- for(int freq=highestFreq; freq >=1; freq--)
- {
- if(dictFreq.ContainsKey(freq))
- {
- foreach(var n in dictFreq[freq])
- {
- Output.Add(n);
- if(Output.Count == k)
- return Output;
- }
- }
- }
- return Output;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement