【问题标题】:Find 2 missing numbers in an array of integers with two missing values在具有两个缺失值的整数数组中查找 2 个缺失数字
【发布时间】:2013-11-30 07:57:27
【问题描述】:

你是怎么做到的?这些值未排序,但属于[1..n] 示例数组[3,1,2,5,7,8]。答:4, 6

我在另一个类似的post看到了这个解决方案,但是我不明白最后一步:

  • 求数字 S=a1+...+an 的总和。
  • 还求平方和 T=a1²+...+an²。
  • 你知道总和应该是 S'=1+...+n=n(n+1)/2
  • 您知道平方和应该是 T'=1²+...+n²=n(n+1)(2n+1)/6。
  • 现在建立以下方程组 x+y=S'-S, x²+y²=T'-T。
  • 通过写作 x²+y²=(x+y)²-2xy => xy=((S'-S)²-(T'-T))/2 求解。
  • 现在这些数字只是 z 中二次方的根:z²-(S'-S)z+((S'-S)²-(T'-T))/2=0。

在最后一步建立以 z 为未知数的二次方程的解释是什么?这个问题的解决方案背后的直觉是什么?

【问题讨论】:

  • 如果您看到的帖子(并且没有链接供参考)没有很好地解释它,是否有什么建议我们可以?
  • 我刚刚链接到它。对我来说,其他人可能能够解释的是这样一个事实,即它看起来不像是某种过于神秘的算法,而我使用链接资源的理解由于其简洁性而已经停滞不前。
  • 这似乎是一种扭曲的处理方式。遍历列表会更简单,查找i 的两个值,例如a[i+1]-a[i] != 1。由于显示的算法还必须遍历数组中的所有值,所以二次方程没有明显的优势——当数据有序时。如果不能保证数据的顺序,则二次方程的解需要线性时间 (O(N)),而排序的解需要 O(N.log(N)) 时间。
  • 这可能比 C++ 更涉及数学。
  • AFAIK 这个问题在求职面试中非常典型。显然,在“原始”版本中,输入数组没有排序。

标签: java c++ arrays algorithm math


【解决方案1】:

不建议使用此方法,因为它存在integer 溢出问题。所以使用XOR方法来查找这两个数字,这是高性能的。如果你有兴趣我可以解释。

根据下面@ordinary的要求,我正在解释算法:

编辑

假设数组a[] 的最大元素是B,即假设a[]={1,2,4} 并且这里3 和5 不存在于a[] 中,所以最大元素是B=5。

  • xor数组的所有元素a到X
  • xor 从 1 到 B 到 x 的所有元素
  • 通过x = x &(~(x-1));找到x最左边的位集
  • 现在如果a[i] ^ x == x 比xor a[i] 到p 否则xor 和q
  • 现在对于从 1 到 B 的所有 k 如果 k ^ x == x 比 xor 和 p 否则 xor 和 q
  • 现在打印p 和q

证明:

让a = {1,2,4} 和B 为5,即从1 到5,缺少的数字是3 和5

一旦我们 XOR 的元素 a 和从 1 到 5 的数字,我们留下了 XOR 的 3 和 5,即 x。

现在,当我们找到x 的最左边位集时,它只不过是 3 和 5 中最左边的不同位。(3--> 011、5 --> 101 和 x = 010 其中x = 3 ^ 5)

在这之后,我们试图根据x的位集分为两组,所以两组将是:

p = 2 , 2 , 3 (all has the 2nd last bit set)

q = 1, 1, 4, 4, 5 (all has the 2nd last bit unset)

如果我们XORp 的元素在它们之间,我们将找到3,类似地,如果我们xorq 的所有元素在它们之间,我们将得到 5。 因此得到了答案。

java中的代码

public void findNumbers(int[] a, int B){
    int x=0;
    for(int i=0; i<a.length;i++){
        x=x^a[i];
    }
    for(int i=1;i<=B;i++){
        x=x^i;
    }
    x = x &(~(x-1));
    int p=0, q=0;
    for(int i=0;i<a.length;i++){
        if((a[i] & x) == x){
            p=p^a[i];
        }
        else{
            q=q^a[i];
        }   
    }
    for(int i=1;i<=B;i++){
        if((i & x) == x){
            p=p^i;
        }
        else{
            q=q^i;
        }
    }

    System.out.println("p: "+p+" : "+q);
}

【讨论】:

  • 我很感兴趣。我知道如果缺少一个数字,您可以将第一个中的所有数字与第二个中的所有数字进行异或,结果将是缺少的数字,但是您如何处理两个呢?
  • 你不是说找到最合适的位吗? (或最低有效位)
  • @ordinary 只需映射您拥有的和想要实现的目标。 :)
  • 这行代码看不懂,请解释一下:x = x &(~(x-1));
  • "所以用异或法求两个数,性能很好。"您应该提到,尽管您的方法需要 4 次迭代(2 次遍历数组),而原始数组仅需要 1 次遍历,因此取决于数组大小,您的方法可能会明显变慢。
【解决方案2】:

设 x 和 y 为二次方程的根。

  • 根之和,SUM = x + y
  • 根的乘积,PRODUCT = x * y

如果我们知道和和乘积,我们可以将二次方程重构为:

z^2 - (SUM)z + (PRODUCT) = 0

在你提到的算法中,我们找到和和乘积,然后使用上面的公式重构二次方程。

如果您对详细推导感兴趣,here is a reference。阅读“从根的和乘积重构二次方程”。

【讨论】:

    【解决方案3】:

    开始

    x+y == SUM
    xy == PRODUCT
    

    有两种情况。如果 PRODUCT 为零,则一个数字是 0,另一个是 SUM。否则两者都不为零;我们可以将第一个等式乘以x 而不会改变等式:

    x*x + xy == x*SUM
    

    代入第二个方程:

    x*x + PRODUCT = x*SUM
    

    并以通常的形式重新排列

    x*x - x*SUM + PRODUCT = 0
    

    这样

    x = SUM/2 + sqrt(SUM*SUM - 4*PRODUCT)/2
    y = SUM/2 - sqrt(SUM*SUM - 4*PRODUCT)/2
    

    【讨论】:

      【解决方案4】:

      我有解决上述问题的算法。

      假设

      Actual Series: 1 2 3 4 5 6          a:sum=21 product= 720
      Missing Number series: 1 * 3 4 * 6  b:sum=14 product= 72
      
      a+b=21-14= 7 , ab=720/72=10
      

      现在我们需要找到a-b= sqrt[(a+b)^2 -4ab]。

      如果你计算:

      a-b= 3
      

      现在

      a+b=7
      a-b=3
      

      添加两个方程:

      2a=10, a=5
      

      那么b=7-5=2 所以,2 和 5 都不见了。

      【讨论】:

      • 如何(加法转为减法)a+b=21-14= 7 乘积转为除法ab=720/72=10?请解释
      • @VivekSingh a + b + 14(缺失数字的系列总和)= 21(包括缺失数字 a 和 b 的总和)这就是为什么 a + b = 21 - 14 ,同样适用产品也是如此
      【解决方案5】:

      Java 实现:(基于@Ben Voigt)

      BigInteger fact=1;
      int sum=0;
      int prod=1;
      int x,y; // The 2 missing numbers
      int n=a.length;
      int max=MIN_VALUE;
      
      for (int i=0; i<a.length;i++){
        sum+=a[i]; //sums the existing numbers
        prod*=a[i]; //product the existing numbers
        if (max<a[i]) //searches for the biggest number in the array
           max=a[i];
      }
      
      while(max!=1){ //factorial for the maximum number
           fact*=max;
           max--;
      }
      sum=(n*(n+1))/2 - sum; //the sum of the 2 missing numbers
      prod=fact/prod; //the product of the 2 missing numbers
      
      x=sum/2 + Math.sqrt(sum*sum - 4*prod)/2;
      y=sum/2 - Math.sqrt(sum*sum - 4*prod)/2;
      

      【讨论】:

      • 请注意,该问题提供了一种在数值上更稳定的方法来查找 xy,它基于平方和而不是阶乘。
      【解决方案6】:

      适用于任意数量的缺失元素: 您可以稍微格式化代码.. 但它也适用于重复和非重复条目:

      public static void main(String args[] ) throws Exception {
      
              Scanner input = new Scanner(System.in);
              System.out.println("Enter no. of students in the class");
              int N = input.nextInt();
              List<Integer> l = new ArrayList<Integer>();
              int Nn=N;
              System.out.println("Enter the roll numbers");
              for(int i=0;i<Nn;i++)
              {
                  int enter=input.nextInt();
      
                  l.add(enter);      
              }
              Collections.sort(l);
              Integer listarr[]=new Integer[l.size()];
              listarr =l.toArray(listarr);
      
      
              int check=0;
              int m1[]=new int[N];
              for(int i=0;i<N;i++)
              {
                  m1[i]=i+1;
              }
      
              for (int i = 0; i < N; i++) {
                    boolean flag=false;
      
                  {
                      for (int j = 0; j < listarr.length; j++) {
      
                          if(m1[i]==listarr[j])
                          { 
                              flag=true;
                              break;
      
                          }
                          else
                          {
      
                          flag=false;
      
                          }
                  }
                      if(flag==false)
                      {
                          System.out.println("Missing number Found : " + m1[i]);
                      }
      
              }
      
      
          }
      

      【讨论】:

        【解决方案7】:
        Below is the generic answer in java code for any number of missing numbers in a given array
        //assumes that there are no duplicates
        a = [1,2,3,4,5]
        b = [1,2,5]
        a-b=[3,4]
        
        public list<integer> find(int[] input){
          int[] a= new int[] {1,2,3,4,5};//create a new array without missing numbers
          List<Integer> l = new ArrayList<Integer>();//list for missing numbers
          Map<Integer,Integer> m = new HashMap<Integer>();
        
          //populate a hashmap with the elements in the new array
          for(int i=0;i<input.length;i++){  
           m.put(input[i], 1);
          }
        //loop through the given input array and check for missing numbers
         for(int i=0;i<a.length;i++){
          if (!m.contains(input[i]))
           l.add(input[i]);
        }
         return l;
        }
        

        【讨论】:

          【解决方案8】:

          我希望这个程序对大家有用,我把限制设置为 10 可以用相同的方式完成,只需使用 n 作为限制并执行相同的操作。

          #include <iostream>
          #include<math.h>
          
          using namespace std;
          
          int main()
          {
              int i,x[100],sum1=0,sum2=0,prod1=1,prod2=1,k,j,p=0;
              cout<<"Enter 8 elements less than 10, they should be non recurring"<<endl;
              for(i=0;i<8;i++)
              {
                  cin>>x[i];
              }
              sum1=((10)*(11))/2;
              for(i=0;i<8;i++)
              {
                  sum2+=x[i];
              }
              k=sum1-sum2;
              for(i=1;i<10;i++)
              {
                  prod1=prod1*i;
              }
              for(i=0;i<8;i++)
              {
                  prod2=prod2*x[i];
              }
              j=prod1/prod2;
              p=sqrt((k*k)-(4*j));
              cout<<"One missing no:"<<p/2<<endl;
              cout<<"Second missing no:"<<k-p/2<<endl;
          
          
          }
          

          【讨论】:

          • 请注意,该问题提供了一种在数值上更稳定的方法来查找 xy,它基于平方和而不是迭代乘积。
          【解决方案9】:
          #include <stdio.h>
          #include <math.h>
          
          /*
              the sum should be 1+...+n = n(n+1)/2
              the sum of squares should be 1^2+...+n^2 = n(n+1)(2n+1)/6.
          */
          
          void find_missing_2_numbers(int *arr, int n);
          
          int main()
          {
              int arr[] = {3,7,1,6,8,5};
          
              find_missing_2_numbers(arr, 8);
          
              return 0;
          }
          
          void find_missing_2_numbers(int *arr, int n)
          {
          
              int i, size, a, b, sum, sum_of_sqr, a_p_b, as_p_bs, a_i_b, a_m_b;
              size = n - 2;
          
              sum = 0;
              sum_of_sqr = 0;
              for (i = 0; i < size; i++)
              {
                  sum += arr[i];
                  sum_of_sqr += (arr[i] * arr[i]);
              }
          
              a_p_b = (n*(n+1))/2 - sum;
              as_p_bs = (n*(n+1)*(2 * n + 1))/6 - sum_of_sqr;
              a_i_b = ((a_p_b * a_p_b) - as_p_bs ) / 2;
              a_m_b = (int) sqrt((a_p_b * a_p_b) - 4 * a_i_b);
              a = (a_p_b + a_m_b) / 2;
              b = a_p_b - a;
          
              printf ("A: %d, B: %d\n", a, b);
          }
          

          【讨论】:

            【解决方案10】:
            public class MissingNumber{
            
            static int[] array = { 1, 3, 5 };
            
            public static void getMissingNumber() {
            
            for (int i = 0; i < array.length; i++)
                System.out.println(array[i] + " ");
            
            System.out.println("The Missing Number is:");
             int j = 0;
            for (int i = 1; i <= 5; i++) {
                if (j < array.length && i == array[j])
                j++;
                else
                System.out.println(i + " ");
            }
            
            }
            public static void main(String[] args) {
            getMissingNumber();
            }
            

            }

            【讨论】:

              【解决方案11】:

              @slider 答案的代码示例(Java)

               /**
                   * get 2 missed numbers from randomly shuffled array of unique elements from [1,n]
                   *
                   * @param array - shuffled array of unique elements from [1,n], but 2 random elements was missed. len = n-2
                   * @return array with 2 missed elements
                   */
                  public static int[] getMissedNumbers(int[] array) {
              
                      int sum = 0;
                      int fullSum = 0;
                      int fullProduct = 1;
                      int product = 1;
                      for (int i = 0; i < array.length + 2; i++) {
                          int currNaturalNumber = i + 1;
                          fullSum = fullSum + currNaturalNumber;
                          fullProduct = fullProduct * currNaturalNumber;
              
                          if (i < array.length) {
                              sum = sum + array[i];
                              product = product * array[i];
                          }
                      }
              
                      int missedSum = fullSum - sum; //firstMissedNum + secondMissedNum
                      int missedProduct = fullProduct / product; //firstMissedNum * secondMissedNum
              
                      //ax*x + bx + c = 0
                      //x = (-b +- sqrt(b*b - 4*a*c))/2*a
                      // -b = missedSum , c = missedProduct, a = 1
                      Double firstMissedNum = (missedSum + Math.sqrt(missedSum * missedSum - 4 * missedProduct)) / 2;
                      Double secondMissedNum = (missedSum - Math.sqrt(missedSum * missedSum - 4 * missedProduct)) / 2;
                      return new int[]{firstMissedNum.intValue(), secondMissedNum.intValue()};
                  }
              

              以及用于测试的简单数组生成器

                public static Map.Entry<int[], int[]> generateArray(int maxN, int missedNumbersCount) {
                      int[] initialArr = new int[maxN];
                      for (int i = 0; i < maxN; i++) {
                          initialArr[i] = i + 1;
                      }
                      shuffleArray(initialArr);
                      int[] skippedNumbers = Arrays.copyOfRange(initialArr, maxN - missedNumbersCount, maxN);
                      int[] arrayWithoutSkippedNumbers = Arrays.copyOf(initialArr, maxN - missedNumbersCount);
                      return new AbstractMap.SimpleEntry<>(arrayWithoutSkippedNumbers, skippedNumbers);
              
                  }
              
                  private static void shuffleArray(int[] ar) {
                      Random rnd = ThreadLocalRandom.current();
                      for (int i = ar.length - 1; i > 0; i--) {
                          int index = rnd.nextInt(i + 1);
                          // Simple swap
                          int a = ar[index];
                          ar[index] = ar[i];
                          ar[i] = a;
                      }
                  }
              

              【讨论】:

                【解决方案12】:
                #include <iostream>
                using namespace std;
                int main() {
                    int arr[]={3,1,2,5,7,8};
                    int n=6;
                    for(int i=0;i<n;i++){
                        if(arr[i]>0 && arr[i]<=n){
                            int temp=arr[i]-1;
                            if(arr[i]!=arr[temp]){
                            swap(arr[i],arr[temp]);
                            i--;
                            }
                        }
                    }
                    for(int i=0;i<n;i++){
                        if(arr[i]!=i+1)
                        cout<<i+1<<endl;
                    }
                    // your code goes here
                    return 0;
                }
                

                我们可以使用与存储桶相同的数组。我们遍历它一次并继续将元素交换到正确的索引。 如果该值小于 1 或大于数组长度,则保持原样。 初始数组- 3 1 2 5 7 8 交换(3,5) 5 1 2 3 7 8 交换(5,8) 8 1 2 3 7 5 在此之后,我们再次遍历数组。不在正确位置的元素丢失了,因此我们打印索引。 时间复杂度-O(n)

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2015-07-20
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多