You can sort the elements by their appearance and take the k-th element:
int[] orderedByOccurence = a.OrderByDescending(i => counts[i]).ToArray();
if (orderedByOccurence.Length > k)
Console.WriteLine($"{k}th most common element: {orderedByOccurence[k]});
But, as Adam pointed out in the comments, you can shorten your code using GroupBy:
private static int KthCommonElement(int[] a, int k)
{
if (a == null) throw new ArgumentNullException(nameof(a));
if (a.Length == 0) throw new ArgumentException();
if (k < 0) throw new ArgumentOutOfRangeException();
var ordered = a.GroupBy(i => i, (i, o) => new { Value = i, Occurences = o.Count()})
.OrderByDescending(g => g.Occurences)
.ToArray();
int index = k;
if (ordered.Length <= index)
{
index = ordered.Length - 1;
}
var result = ordered[index];
Console.WriteLine("The most common number is {0} and it appears {1} times",
result.Value, result.Occurrences);
return result.Value;
}
source
share