所以这是我的问题代码。当我尝试传递一个带有N个参数的数组时,让我们说{2,1,2,2,5}结果我想获得二维secArray [元素,元素的频率]。问题是我得到的不仅仅是这个,在这种特殊情况下,我得到一个这样的数组: 23 11 22 21 52
Console.WriteLine("Enter number of elements: ");
int n = int.Parse(Console.ReadLine());
int[] array = new int[n];
for (int i = 0; i < array.Length; i++)
{
Console.Write("Array[{0}]: ", i);
array[i] = int.Parse(Console.ReadLine());
}
//problematic code begins
int[,] secArray = new int[n,2];
for(int i = 0;i<n;i++)
{
for(int j = 0; j<n;j++)
{
if(array[i] == secArray[j,0])
{
secArray[j, 1] += 1;
}
else
{
secArray[i, 0] = array[i];
secArray[i, 1] = 1;
}
}
}
//problematic code ends
//printing - works good
Console.WriteLine("How many same elements?");
for (int row = 0; row < secArray.GetLength(0); row++)
{
for (int col = 0; col < secArray.GetLength(1); col++)
{
Console.Write(secArray[row, col]);
}
Console.WriteLine();
}
如果有人知道如何解决这个问题,我将非常感激。我不知道我不知道实际问题在哪里。
答案 0 :(得分:1)
我会使用Linq的 GroupBy 来执行此操作
var array = new int[] { 2, 1, 2, 2, 5 };
var result = array.GroupBy(x => x).Select(x => new[] { x.Key, x.Count() }).ToArray();
答案 1 :(得分:1)
第一个问题涉及第一个问题。
int[,] secArray = new int[n,2];
在遍历数组之前,您不知道数组中有多少个唯一元素。你不能使用n,因为n是参数的总数,它可以大于唯一元素的数量。
接下来,嵌套的for循环非常低效。您的算法遍历数组中每个元素的数组 - 因此它将在O(n ^ 2)时间内运行。
想一想:你不得不多次遍历数组吗?为什么不只是在遍历数组时使用散列表(C#中的字典)来跟踪计数?哈希表使用非常有效的查找机制来告诉您是否已经看过该元素,并且该值可用于跟踪计数。
考虑使用以下内容替换有问题的代码,并了解其工作原理。
Dictionary<int, int> elementCounts = new Dictionary<int, int>();
for(int i = 0; i < n; i++)
{
int element = array[i];
if (elementCounts.ContainsKey(element))
elementCounts[element]++;
else
elementCounts.Add(element, 1);
}
Console.WriteLine("How many same elements?");
foreach(KeyValuePair<int,int> count in elementCounts)
{
Console.WriteLine("Element: {0} Count: {1}", count.Key, count.Value);
}
然后,如果要将哈希表(Dictionary)中的结果复制到二维数组,可以执行以下操作。
int numberOfUniqueElements = elementCounts.Count;
int[,] secArray = new int[numberOfUniqueElements, 2];
int j = 0;
foreach (KeyValuePair<int, int> count in elementCounts)
{
secArray[j, 0] = count.Key;
secArray[j, 1] = count.Value;
j++;
}
答案 2 :(得分:0)
为什么不使用哈希表。让数组中的数字为散列条目键,并使散列条目的值为计数。然后只需迭代一次数组。迭代遍历数组时检查是否存在哈希条目,如果是,则向其添加1,如果不创建它。
像
这样的东西for(int i = 0; i<n;i++) {
if(hashTable.containsKey(array[i])) {
hashTable[array[i]]++];
} else {
hashTable.add(array[i],1);
}
}
请注意,这是quedocode,需要查找方法并正确实现。