C# How to make recursive function to return the nth most common integer in an array of integers
I am using c# and I am looking for the most memory efficient way to sort a list of integers by how often they appear in an integer array and then return the nth array element where nth is an integer represent the descending order key of choice (most used integer, 2nd most used integer, 3rd most used integer, etc.
I can do this using linq with something like this...
public static void Main(string[] args)
{
int x = NthMostCommon(new int[] { 5, 4, 3, 2, 1, 5, 4, 3, 2, 5, 4, 3, 5, 4, 5 }, 2);
Console.WriteLine(x);
}
private static int NthMostCommon(int[] a, int k)
{
int result = 0;
var query = a.GroupBy(item => item).OrderByDescending(g => g.Count());
if (query.Count() >= k)
{
result = query.ElementAt(k - 1).Key;
}
return result;
}
This works, but I have been told that this is not the most memory efficient way of getting the desired result when working with larger integer arrays. I cannot see how I can reduce the memory footprint. I have to iterate the entire array, regardless of the size. Yes?
Any ideas?
Thanks in advance.