如何在数组中查找重复项并显示重复次数? [英] How do I find duplicates in an array and display how many times they occurred?
本文介绍了如何在数组中查找重复项并显示重复次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究一个代码,该代码从数组中打印出重复的整数及其出现的次数.我不被允许使用LINQ,只是一个简单的代码.我想我是如此亲密,但对如何获得正确的输出感到困惑:
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();
}
}
}
推荐答案
由于您无法使用LINQ,因此可以使用集合和循环来实现:
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屋!
查看全文