如题, 那天去moto 面试,面试官问了我一个问题,我觉得我没有答好,看各位有没有啥子好的方法1-100个数,不重复的随机插入到维数为99的数组,请用最有高效的方法查出这100个数中那一个数是没有插入到数组中的?

解决方案 »

  1.   


            int GetMissingValue(int[] allValues, int[] samples)
            {
                int result = 0;
                for (int i = 0; i < samples.Length; i++)
                {
                    result ^= allValues[i];
                    result ^= samples[i];
                }
                return result ^ allValues[ allValues.Length - 1 ];
            }        // 测试(4个数到3个槽位)
            public void Test()
            {
                int[] numbers = new int[] { 1,3,5,7,2};
                int[] samples = new int[] { 1,3,2,5  };            int result = GetMissingValue(numbers, samples);      // result = 7
            }
      

  2.   

    总和-累加和...例:
    int[] iis = { 1, 2, 3, 4, 5, 7, 8, 9, 10 };
    int i = 55 - iis.Sum();
      

  3.   

    公式是:(max + 1) * max / 2 - array.Sum();
      

  4.   

    学习了,(max + 1) * max / 2 - array.Sum();
    这个公式就可以找到结果。