Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2] .
Note:
- You may assume K are always valid, 1≤ k ≤number of unique elements.
- Your algorithm's time complexity must be better than O (n log n), where n is the array ' s size.
Using Count Sort
Publicilist<int> Topkfrequent (int[] Nums,intk) {varres =Newlist<int>(); if(Nums. Count () = =0)returnRes; varHashtable =Newdictionary<int,int>(); for(inti =0;i< Nums. Count (); i++) { if(Hashtable. ContainsKey (Nums[i]) hashtable[nums[i]]++; ElseHashtable. ADD (Nums[i],1); } //Sort by Count sort varDP =Newlist<int>(); foreach(varPairinchHashtable) {DP. ADD (pair. Value); } intA =FINDK (dp,k); foreach(varPairinchHashtable) { if(pair.) Value >=a) Res. ADD (pair. Key); } returnRes; } Public intFINDK (list<int> Nums,intk) {if(Nums. Count () = =0)return 0; intmax = nums[0]; intMin = nums[0]; varb =New int[Nums. Count ()]; foreach(intNinchnums) {Max=Math.max (max,n); Min=math.min (min,n); } intKK = Max-min +1; varc =New int[KK]; for(inti =0; I<nums. Count (); i++) {C[nums[i]-min] + =1; } for(inti =1; I<c.count (); i++) {C[i]= C[i] + c[i-1]; } for(inti = Nums. Count ()-1; I >=0; i--) {b[--c[nums[i]-min]] =Nums[i]; } returnB[nums. Count ()-K]; }
347. Top K Frequent Elements