Algorithm to find two repeated numbers in an array, without sorting

前端 未结 24 2012
南方客
南方客 2020-11-28 06:58

There is an array of size n (numbers are between 0 and n - 3) and only 2 numbers are repeated. Elements are placed randomly in the array.

E.g. in {2, 3, 6, 1, 5, 4

相关标签:
24条回答
  • 2020-11-28 07:06

    You know that your Array contains every number from 0 to n-3 and the two repeating ones (p & q). For simplicity, lets ignore the 0-case for now.

    You can calculate the sum and the product over the array, resulting in:

    1 + 2 + ... + n-3 + p + q = p + q + (n-3)(n-2)/2
    

    So if you substract (n-3)(n-2)/2 from the sum of the whole array, you get

    sum(Array) - (n-3)(n-2)/2 = x = p + q
    

    Now do the same for the product:

    1 * 2 * ... * n - 3 * p * q = (n - 3)! * p * q
    
    prod(Array) / (n - 3)! = y = p * q
    

    Your now got these terms:

    x = p + q
    
    y = p * q
    
    => y(p + q) = x(p * q)
    

    If you transform this term, you should be able to calculate p and q

    0 讨论(0)
  • 2020-11-28 07:07

    check this out ... O(n) time and O(1) space complexity

     for(i=0;i< n;i++)
     xor=xor^arr[i]
     for(i=1;i<=n-3;i++)
     xor=xor^i;
    

    So in the given example you will get the xor of 3 and 5

    xor=xor & -xor  //Isolate the last digit
    
    for(i = 0; i < n; i++)
    {
    if(arr[i] & xor)
      x = x ^ arr[i]; 
    else
      y = y ^ arr[i]; 
    }
    for(i = 1; i <= n-3; i++)
    {
    if(i & xor)
      x = x ^ i; 
    else
      y = y ^ i; 
    

    }

    x and y are your answers

    0 讨论(0)
  • 2020-11-28 07:09

    For each number: check if it exists in the rest of the array.

    0 讨论(0)
  • 2020-11-28 07:10

    There is a O(n) solution if you know what the possible domain of input is. For example if your input array contains numbers between 0 to 100, consider the following code.

    bool flags[100];
    for(int i = 0; i < 100; i++)
        flags[i] = false;
    
    for(int i = 0; i < input_size; i++)
        if(flags[input_array[i]])
             return input_array[i];
        else       
            flags[input_array[i]] = true;
    

    Of course there is the additional memory but this is the fastest.

    0 讨论(0)
  • 2020-11-28 07:10

    You might be able to take advantage of the fact that sum(array) = (n-2)*(n-3)/2 + two missing numbers.

    Edit: As others have noted, combined with the sum-of-squares, you can use this, I was just a little slow in figuring it out.

    0 讨论(0)
  • 2020-11-28 07:11

    Without sorting you're going to have a keep track of numbers you've already visited.

    in psuedocode this would basically be (done this way so I'm not just giving you the answer):

    for each number in the list
       if number not already in unique numbers list
          add it to the unique numbers list
       else
          return that number as it is a duplicate
       end if
    end for each
    
    0 讨论(0)
提交回复
热议问题