【发布时间】:2017-07-17 20:41:01
【问题描述】:
我想从数组中找出第 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;
}
【问题讨论】:
-
这必须有多高效?它是否需要比完整排序更高效?