我希望您能够找到一个数组中第k个最常见的元素,我已经成功找到了最常见的元素,但是我不知道如何找到第k个常见的元素。
我尝试过以下方法:
我尝试过以下方法:
private static int KthCommonElement(int[] a, int k)
{
var counts = new Dictionary<int, int>();
foreach (int number in a)
{
int count;
counts.TryGetValue(number, out count);
count++;
//Automatically replaces the entry if it exists;
//no need to use 'Contains'
counts[number] = count;
}
int mostCommonNumber = 0, occurrences = 0;
foreach (var pair in counts)
{
if (pair.Value > occurrences)
{
occurrences = pair.Value;
mostCommonNumber = pair.Key;
}
}
Console.WriteLine("The most common number is {0} and it appears {1} times", mostCommonNumber, occurrences);
return mostCommonNumber;
}