sun*_*wer 20 c# arrays duplicates
我正在编写一个代码,用于打印出数组中重复的整数及其出现次数.我不允许使用LINQ,只是一个简单的代码.我想我是如此接近但对如何获得正确的输出感到困惑:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ree*_*sey 50
由于您无法使用LINQ,因此您可以使用集合和循环来执行此操作:
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();
}
Run Code Online (Sandbox Code Playgroud)
小智 14
使用分组依据:
int[] values = new []{1,2,3,4,5,4,4,3};
var groups = values.GroupBy(v => v);
foreach(var group in groups)
Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());
Run Code Online (Sandbox Code Playgroud)
我们来看一个更简单的例子.假设我们有阵列{0, 0, 0, 0}
.
你的代码会做什么?
它首先会查看第一个项目后面有多少项目.第一个之后有三个项目等于它.
然后它转到下一个项目,并在其后面查找与其相等的所有项目.那里有两个.到目前为止,我们已经到了5,我们还没有完成(我们还有一个要添加),但整个数组中只有四个项目.
显然我们在这里有一个问题.我们需要确保当我们在数组中搜索给定项目的副本时,我们不再为同一项目搜索它.虽然有办法做到这一点,但这种基本方法看起来是相当多的工作.
当然,我们可以采取不同的方法.相反,遍历每个项目并搜索其他类似项目,我们可以遍历数组一次,并添加到我们找到该字符的次数.使用a Dictionary
可以轻松实现:
var dictionary = new Dictionary<int, int>();
foreach (int n in array)
{
if (!dictionary.ContainsKey(n))
dictionary[n] = 0;
dictionary[n]++;
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以循环遍历字典并查看多次找到哪些值:
foreach(var pair in dictionary)
if(pair.Value > 1)
Console.WriteLine(pair.Key);
Run Code Online (Sandbox Code Playgroud)
这使代码清晰易读,明显正确,并且(作为奖励)比代码更有效,因为您可以避免多次循环遍历集合.
这是避免使用字典的答案。由于OP说他对它们不熟悉,这可能会让他对词典的作用有一些了解。
这个答案的缺点是你必须对数组中的最大数量施加限制,并且不能有负数。您永远不会在实际代码中实际使用此版本。
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int[] count = new int[13];
foreach(int number in array) {
// using the index of count same way you'd use a key in a dictionary
count[number]++;
}
foreach(int c in count) {
int numberCount = count[c];
if(numberCount > 0) {
Console.WriteLine(c + " occurs " + numberCount + " times");
}
}
Run Code Online (Sandbox Code Playgroud)