首页 > 技术文章 > A B两个相同长度整数数组,判断相同下标对应值是否相等,true或者false 存在布尔数组C中

lilixiang-go 2015-10-19 10:25 原文

问题描述:A B两个相同长度整数数组,判断相同下标对应值是否相等,true或者false 存在布尔数组C中。

一:常规操作就是利用数组的方法   if (B.Contains(A[i])) C[i] = true;

二:利用hashset  hashtable   directionary   list等集合表,速度提升明显,

三:博客园一哥们为解决另一个哥们问题想到的方法。因为数组A、B都是int,所以可以把A、B作为C的索引考虑。不晓得这哥们怎么想到的,不过亲测速度的确快。

 static void ValidateArrayElement()
        {
            Stopwatch sp = new Stopwatch();
            sp.Start();
            Random rand = new Random();
            Int32 maxValue = 120000;//元素最大值,是一个假定值
            Int32 length = 70000;// A,B的长度
            Int32[] A = new Int32[length];
            Int32[] B = new Int32[length];
            Boolean[] C = new Boolean[length];
            Boolean[] Atemp = new Boolean[maxValue];//临时的辅助变量
            //随机初始化A,B数组
            for (int i = 0; i < length; i++)
            {
                A[i] = rand.Next(maxValue);
                B[i] = rand.Next(maxValue);
            }
            //循环B,验证元素是否存在
            foreach (var item in B) Atemp[item] = true;
            //循环A,验证是否存在,将C对应位置标记为true
            for (int i = 0; i < A.Length; i++) if (Atemp[A[i]]) C[i] = true;
            sp.Stop();//停止计时
            Console.WriteLine(sp.ElapsedMilliseconds);
            Console.ReadKey();
        }

 

推荐阅读