在c#中只打印一次重复的数字
我有一个包含“n”个数字的数组,我只需在
编写此代码时打印一次所有重复的数字,但
for (int i = 0; i < numbers.Length; i++)
{
for (int j = 1; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j] && i!=j)
{
Console.WriteLine(numbers[i]);
break;
}
}
}
具有元素 {2,3,1,5,2,3} ,则
如果我的数组 出现问题程序打印:
2
3
3
我能做什么?
I have an array with "n" numbers and I need to print all repeated numbers only one time
i made this code, but something is wrong
for (int i = 0; i < numbers.Length; i++)
{
for (int j = 1; j < numbers.Length; j++)
{
if (numbers[i] == numbers[j] && i!=j)
{
Console.WriteLine(numbers[i]);
break;
}
}
}
then if my array have the elements {2,3,1,5,2,3}
the program prints :
2
3
3
what can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用:
编辑
我可能误解了要求。如果你只想输出出现多次的数字,那么你可以使用:
You can use:
edit
I may have misunderstood the requirement. If you only want to output the numbers that appear more than once, then you can use:
或者,另一种选择...
Or, alternatively...
代码中的问题:您会重复 3,因为当 i 为 1(查看第一个
3
)时,列表末尾还有另一个 3,而当 i 为 5(查看最后一个 < code>3)在靠近开头的列表中还有另外三个。相反,您应该只查看当前位置之后的数字 - 更改为
int j = i;
这样您就只查看当前位置之后的位置,并且不会得到重复的结果。话虽如此,您的算法不如使用内置算法有效。尝试
GroupBy
The problem in your code: you get 3 repeated because when i is 1 (looking at the first
3
) there's another 3 in the list at the end, and when i is 5 (looking at the last3
) there's another three in the list near the beginning.Instead you should look at only those numbers which come after your current position - change to
int j = i;
so that you only look at the positions after your current position, and you won't get repeated results.Having said that, your algorithm is not as efficient as using a built in algorithm. Try
GroupBy
获取不同数字的一种方法是
然后迭代 uniqueNumbers,就像您在代码片段中使用数字一样。
One way to get distinct numbers is
and then iterate over uniqueNumbers like you have in your snippet with numbers.
您可以在循环时将数字添加到哈希集中,然后仅在不在哈希集中时才打印。
这使您可以一次性完成此操作。
上面的算法是n^2,应该避免。
You can add the number to a HashSet as you loop and then only print if not in hash set.
That allows you to do it in one pass.
The algorithm above is n^2 which should be avoided.