Skip to content

Instantly share code, notes, and snippets.

@letscodego
Created August 13, 2022 06:40
Show Gist options
  • Save letscodego/3b78465b64365fa057ddad328943382e to your computer and use it in GitHub Desktop.
Save letscodego/3b78465b64365fa057ddad328943382e to your computer and use it in GitHub Desktop.
public static int[] TopKFrequent(int[] nums, int k)
{
if (nums.Length == 0 || k == 0)
return Array.Empty<int>();
var result = new List<int>();
Dictionary<int, int> dic = new Dictionary<int, int>();
foreach (var item in nums)
{
if (dic.ContainsKey(item))
dic[item]++;
else
dic.Add(item, 1);
}
return dic.OrderByDescending(x => x.Value).Select(x => x.Key).Take(k).ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment