Advertisement
rishu110067

Untitled

Feb 24th, 2022
937
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | None | 0 0
  1. public static List<int> find_top_k_frequent_elements(List<int> arr, int k) {
  2.         List<int> Output = new List<int>();
  3.        
  4.         Dictionary<int,int> numsList = new Dictionary<int,int>();
  5.        
  6.         foreach(int ele in arr){
  7.             if(numsList.ContainsKey(ele))
  8.                 numsList[ele] += 1;
  9.             else
  10.                 numsList.Add(ele,1);
  11.         }
  12.        
  13.         Dictionary<int,List<int>> dictFreq = new Dictionary<int,List<int>>();
  14.         int highestFreq = 0;
  15.         foreach(KeyValuePair<int, int> kvp in numsList){
  16.            
  17.             highestFreq = Math.Max(highestFreq, kvp.Value);
  18.             if(dictFreq.ContainsKey(kvp.Value)){
  19.                 List<int> numbers = dictFreq[kvp.Value];
  20.                 numbers.Add(kvp.Key);
  21.             }
  22.             else{
  23.                 List<int> numbers = new List<int>();
  24.                 numbers.Add(kvp.Key);
  25.                 dictFreq.Add(kvp.Value, numbers);
  26.             }
  27.            
  28.         }
  29.        
  30.         for(int freq=highestFreq; freq >=1; freq--)
  31.         {
  32.             if(dictFreq.ContainsKey(freq))
  33.             {
  34.                 foreach(var n in dictFreq[freq])
  35.                 {
  36.                     Output.Add(n);
  37.                     if(Output.Count == k)
  38.                         return Output;
  39.                 }
  40.             }
  41.         }
  42.        
  43.         return Output;
  44.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement