在一个阵列寻找重复整数并显示他们发生了多少次 [英] Finding duplicate integers in an array and display how many times they occurred
本文介绍了在一个阵列寻找重复整数并显示他们发生了多少次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我工作的一个code,从与他们发生次数阵列打印出重复的整数。我不能使用LINQ,只是一个简单的code。我想我是如此接近,但关于如何得到正确的输出困惑:
类节目
{
静态无效的主要(字串[] args)
{
INT []数组= {10,5,10,2,2,3,4,5,5,6,7,8,9,11,12,12};
诠释计数= 1;
的for(int i = 0; I< array.Length;我++)
{
对于(INT J =; J< array.Length - 1; J ++)
{ 如果(阵列[J] ==阵列[J + 1])
数=计+ 1;
}
Console.WriteLine(\\ t \\ n+阵列[I] +occurse+计数);
Console.ReadKey();
}
}
}
解决方案
既然你不能使用LINQ,你可以用集合做到这一点,而不是循环:
静态无效的主要(字串[] args)
{
INT []数组= {10,5,10,2,2,3,4,5,5,6,7,8,9,11,12,12};
VAR字典=新词典< INT,INT>(); 的foreach(数组VAR值)
{
如果(dict.ContainsKey(值))
字典[值] ++;
其他
字典[值] = 1;
} 的foreach(在字典VAR对)
Console.WriteLine(值{0}发生{1}次。pair.Key,pair.Value);
Console.ReadKey();
}
I'm working on a code that prints out duplicated integers from an array with the number of their occurrence. I'm not allowed to use LINQ, just a simple code. I think I'm so close but confused about how to get a correct output:
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1;
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length - 1 ; j++)
{
if(array[j] == array[j+1])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurse" + count);
Console.ReadKey();
}
}
}
解决方案
Since you can't use LINQ, you can do this with collections and loops instead:
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var dict = new Dictionary<int, int>();
foreach(var value in array)
{
if (dict.ContainsKey(value))
dict[value]++;
else
dict[value] = 1;
}
foreach(var pair in dict)
Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
Console.ReadKey();
}
这篇关于在一个阵列寻找重复整数并显示他们发生了多少次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文