【问题标题】:C# HashSet contains duplicate elementsC# HashSet 包含重复元素
【发布时间】: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#


【解决方案1】:

您的 HashSet 中没有重复项。您正在控制台写入哈希的所有元素,因此这将控制台日志 1 和 2:

foreach (int h in hash)
{
    Console.WriteLine(h);
}

然后,你正在做这个控制台写行:

int[] theArray = new int[] { 1, 1, 2 };
int theValue = RemoveDuplicates(theArray);
Console.WriteLine(theValue);

这将显示哈希中的元素数,这是 2,因此您将在屏幕上看到 1, 2, 2,但前两个数字来自您的哈希集,最后一个来自您的哈希集元素计数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 2013-04-20
    • 2015-03-29
    • 2023-01-17
    • 2015-07-28
    • 2015-06-22
    相关资源
    最近更新 更多