Skip to content

Commit 82252e6

Browse files
authored
Merge pull request #225 from hellomrsun/master
Add Top K Frequent Elements C#
2 parents cec1603 + a3d5518 commit 82252e6

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
public class Solution {
2+
public int[] TopKFrequent(int[] nums, int k) {
3+
//Count occurrence for each value
4+
var dict = new Dictionary<int, int>();
5+
for(int i=0; i<nums.Length; i++){
6+
if(!dict.ContainsKey(nums[i])){
7+
dict.Add(nums[i], 1);
8+
}else {
9+
dict[nums[i]]++;
10+
}
11+
}
12+
13+
//Create array list indexed by occurrence
14+
var numbersByCount = new List<int>[nums.Length+1];
15+
foreach(var kv in dict){
16+
var occurrence = kv.Value;
17+
if(numbersByCount[occurrence] == null){
18+
numbersByCount[occurrence] = new List<int>();
19+
}
20+
numbersByCount[occurrence].Add(kv.Key);
21+
}
22+
23+
//Decrease numbersByCount.Length as the number of occurence, and check the a sublist's existence
24+
var res = new List<int>();
25+
for(int i=numbersByCount.Length-1; i>0 && k>0; i--){
26+
if(numbersByCount[i] != null){
27+
res.AddRange(numbersByCount[i]);
28+
k = k - numbersByCount[i].Count;
29+
}
30+
}
31+
32+
return res.ToArray();
33+
}
34+
}

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ Solutions in various programming languages are provided. Enjoy it.
2222
13. [Same Tree](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/13-Same-Tree): DFS
2323
14. [Angle Between Hands of a Clock](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock): Math
2424
15. [Reverse Words in a String](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String): Pointer
25-
16. [16-Pow(x,n)](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/16-Pow(x,n)): Recursion
26-
25+
16. [Pow(x,n)](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/16-Pow(x,n)): Recursion
26+
17. [Top K Frequent Elements](https://github.com/AlgoStudyGroup/Leetcode/tree/master/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements): Bucket
2727

2828
## June LeetCoding Challenge
2929
Click [here](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) for problem descriptions.

0 commit comments

Comments
 (0)