Skip to content

Instantly share code, notes, and snippets.

@letscodego
Created August 13, 2022 06:38
Show Gist options
  • Save letscodego/122c1cb77cee5eebcdd11d7c218ce9e5 to your computer and use it in GitHub Desktop.
Save letscodego/122c1cb77cee5eebcdd11d7c218ce9e5 to your computer and use it in GitHub Desktop.
TopKFrequent
public static int[] TopKFrequent(int[] nums, int k)
{
//By bucket sort
if (nums.Length == 0 || k == 0)
return Array.Empty();
var result = new List();
Dictionary num2count = new Dictionary();
foreach (var item in nums)
{
if (num2count.ContainsKey(item))
num2count[item]++;
else
num2count.Add(item, 1);
}
List[] bucket = new List[nums.Length + 1];
foreach (var key in num2count.Keys)
{
int frequent = num2count[key];
if (bucket[frequent] == null)
{
bucket[frequent] = new List();
}
bucket[frequent].Add(key);
}
for (var i = bucket.Length - 1; i > 0; i--)
{
if (bucket[i] != null)
{
foreach (var item in bucket[i])
{
result.Add(item);
if (result.Count == k)
return result.ToArray();
}
}
}
return result.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment