【发布时间】:2022-07-05 15:09:47
【问题描述】:
我正在编写代码以使用 HashSet 从数组中删除重复元素。 我看到 HashSet 填充了独特的元素 [见图],但是当我遍历 HashSet 时,我的输出是:[1,2,2]。
任何帮助将不胜感激。谢谢。
请在下面找到我的代码:
int RemoveDuplicates(int[] nums)
{
HashSet<int> hash = new HashSet<int>();
int count = 0;
foreach(int n in nums)
{
hash.Add(n);
}
foreach (int h in hash)
{
Console.WriteLine(h);
}
return count = hash.Count;
}
int[] theArray = new int[] { 1, 1, 2};
int theValue = RemoveDuplicates(theArray);
Console.WriteLine(theValue);
【问题讨论】:
-
输出是你告诉它输出的。
RemoveDuplicates打印 1 和 2,因为它们是唯一的项目。然后,您将 2(哈希集中的项目数)返回给调用者,并打印它,从而输出 1 2 2。此外,您可以使用if (hash.Add(n)) { Console.WriteLine(n); }来避免需要第二个循环。 -
foreach 循环中的第一个
Console.WriteLine(h);打印1 2,最后一个Console.WriteLine(theValue);打印2,因为这是数组中元素的数量(函数的返回值) -
这样更清楚:rextester.com/SZKPU26937
标签: c#