例如...
- 我有一个整数数组,它由 1 到 1000 之间的随机值初始化
- 数组有 1M 个元素(它可能会有更多,但这只是示例)
- 每个元素的出现次数必须在 10 到 1010 之间
调整此数组元素以使其符合上述标准的最快方法是什么?
如果最大出现次数接近 array.Length (1M)/valuesSpan (1000),我的第一个解决方案就太慢了
我尝试了类似的东西(这仅用于对齐出现的最大值,下限的解决方案几乎相同):
Int64[] DistinctArrayElements = distinctArrayElements;
Dictionary<Int64, Int32> occurrences = new Dictionary<Int64, Int32>();
foreach (Int64 DistinctElement in DistinctArrayElements)
{
occurrences.Add(DistinctElement, 0);
}
foreach (Int64 ArrayElement in Arr)
{
occurrences[ArrayElement] += 1;
}
//I know this initialization can be done more nicely, so don't bother with this.
for (int j = 0; j < Arr.Length; j++)
{
if (occurrences[Arr[j]] > upperNoOfOccurrences)
{
for (int i = 0; i < Arr.Length; i++)
{
if (occurrences[Arr[i]] < upperNoOfOccurrences)
{
Arr[j] = Arr[i];
occurrences[Arr[i]] += 1;
occurrences[Arr[j]] -= 1;
}
}
}
}