【算法优化】两组数据,求其中一组的数据在另一组里是否存在
准备数据
Random rand = new Random(); Int32 maxValue = 120000;//元素最大值,是一个假定值 Int32 length = 70000;// A,B的长度 Int32[] A = new Int32[length]; Int32[] B = new Int32[length]; //随机初始化A,B数组 for (int i = 0; i < length; i++) { A[i] = rand.Next(maxValue); B[i] = rand.Next(maxValue); }
比较算法1:用Contains
1 Boolean[] C = new Boolean[length]; 2 3 Stopwatch sp = new Stopwatch(); 4 sp.Start(); 5 //循环A,验证是否存在,将C对应位置标记为true 6 for (int i = 0; i < A.Length; i++) if (B.Contains(A[i])) C[i] = true; 7 sp.Stop(); 8 Console.WriteLine("比较算法用时:" + sp.ElapsedMilliseconds);
比较算法2:
1 Boolean[] C = new Boolean[length]; 2 Boolean[] Atemp = new Boolean[maxValue];//临时的辅助变量 3 4 Stopwatch sp = new Stopwatch(); 5 sp.Start(); 6 //循环B,验证元素是否存在 7 foreach (var item in B) Atemp[item] = true; 8 //循环A,验证是否存在,将C对应位置标记为true 9 for (int i = 0; i < A.Length; i++) if (Atemp[A[i]]) C[i] = true; 10 sp.Stop(); 11 Console.WriteLine("比较算法用时:" + sp.ElapsedMilliseconds);
算法1平均用时3700毫秒,算法2平均用时1毫秒。 以上2个算法都是优化后,但后者更好。 如果用普通的实现方式,性能非常慢。
from:http://www.cnblogs.com/asxinyu/p/dotnet_Algorithm_SamplePrograrm_Time.html
当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--buguge
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/buguge/articles/4892776.html