可以使用哈希表或者计数排序来实现时间复杂度和空间复杂度都为O(n)的查找重复数字元素的算法。以下是哈希表的实现方法:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10, 10 };
HashSet<int> set = new HashSet<int>();
List<int> duplicates = new List<int>();
for (int i = 0; i < arr.Length; i++)
{
if (!set.Add(arr[i]))
{
duplicates.Add(arr[i]);
}
}
if (duplicates.Count == 0)
{
Console.WriteLine("No duplicates found.");
}
else
{
Console.WriteLine("Duplicates found: ");
foreach (int num in duplicates)
{
Console.Write(num + " ");
}
}
}
}
上述代码中,我们使用了哈希表来存储已经出现过的数字。当遍历到一个新的数字时,我们检查该数字是否已经在哈希表中出现过,如果已经出现过,说明这个数字是重复的,我们将其加入到duplicates列表中。最后,我们输出所有重复的数字。
需要注意的是,哈希表的空间复杂度为O(n),而且在处理哈希冲突时可能会有一些额外的开销。如果想要空间复杂度更小的算法,可以使用计数排序来实现。