我的阵列是 A = {2, 3, 4, 3, 4, 2, 4, 2, 4}
我需要一个数组 B,它在索引处存储数组 A 中出现i的次数i。
我想要一个返回的代码:
b[2] = 3
b[3] = 2
b[4] = 4
Run Code Online (Sandbox Code Playgroud)
请记住,如果在上述数组中A添加任何数字也应添加到结果数组中B。
如果有人在这方面帮助我,我将非常感激。
下面给出了我到目前为止所做的代码。
static void Main(string[] args)
{
int [] A = new int[4];
int [] B = new int [A.Length];
for (int i = 0; i > A.Length; i++)
{
B[A[i]] = B[i];
}
}
Run Code Online (Sandbox Code Playgroud)
我是编程新手。我有这个场景来写一个算法,我是第一次写这种类型的算法。
如果您想了解每个项目在数组中出现的次数,例如,您可以使用Linq:
int[] a = new int[]
{ 2, 3, 4, 3, 4, 2, 4, 2, 4 };
// I'd rather not used array, as you suggested, but dictionary
Dictionary<int, int> b = a
.GroupBy(item => item)
.ToDictionary(item => item.Key, item => item.Count());
...
the outcome is
b[2] == 3;
b[3] == 2;
b[4] == 4;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3362 次 |
| 最近记录: |