我有一个包含重复值的数组。我需要显示每个值在数组中出现的次数。
假设我有一个包含8个值的数组,数组={1,2,3,1,1,2,6,7},我需要输出:
1 was found 3 times
2 was found 2 times
3 was found 1 time
6 was found 1 time
7 was found 1 time
这是我的代码。目前我正在将数组中的每个值保存到变量中,然后循环遍历该数组以检查该值是否存在,然后打印出来。
int[] nums = { 2, 4, 14, 17, 45, 48, 5, 6, 16, 25, 28, 33, 17, 26, 35, 44, 46, 49, 5, 6, 20, 27, 36, 45, 6, 22, 23, 24, 33, 39, 4, 6, 11, 14, 15, 38, 5, 20, 22, 26, 29, 47, 7, 14, 16, 24, 31, 32 };
for (int i = 0; i < nums.Length; i++)
{
int s = nums[i];
for (int j = 0; j < nums.Length; j++)
{
if (s == nums[j])
{
Console.WriteLine(s);
}
}
}
提前感谢