如何高效地找出给定数组中的所有重复元素?
using System; public class Test { //删除数组中的重复元素 private static void Main(string[] args) { //构造一个包含大量元素的数组,同时包含多个重复项 int[] arr = new int[100000]; for (int i = 0; i < arr.Length; i++) { arr[i] = (i % 10000) * (new Random().Next(0, 100)) % 10000; } //也可以直接使用C#中现成的方法来实现 //HashSet<int> hash = new HashSet<int>(); //利用HashSet不包含重复项,也不会自动排序的特点 //Array.ForEach(arr, t => hash.Add(t)); //hash.UnionWith(arr); //IEnumerable<int> ie = hash.Union(arr); //新定义一个临时数组,用来标记重复项 int[] temp = new int[arr.Length]; //初始化临时数组中的元素 for (int i = 0; i < arr.Length; i++) { temp[i] = 0; } //记录执行时间 DateTime beforDT = System.DateTime.Now; //查找重复项 for (int i = 0; i < arr.Length; i++) { //检查temp[i]没有被标记,才继续查找 if (temp[i] != -1) { for (int j = i + 1; j < arr.Length; j++) { if (arr[i] == arr[j]) { temp[j] = -1; //test if (j > 50000 && j < 50009) Console.WriteLine("arr[" + i + "]=" + arr[i] + ", arr[" + j + "]=" + arr[j]); } } } } DateTime afterDT = System.DateTime.Now; TimeSpan ts = afterDT.Subtract(beforDT); Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds); //Console.Write(string.Join(",", temp)); Console.ReadKey(); } }
原文:http://www.cnblogs.com/hellowzl/p/6398785.html