Find the missing and duplicate elements in an array in linear time and constant space

后端 未结 8 1368
青春惊慌失措
青春惊慌失措 2020-11-27 14:10

You’re given an array of N 64 bit integers. N may be very large. You know that every integer 1..N appears once in the array, except there is one integer mis

8条回答
  •  天命终不由人
    2020-11-27 14:34

    Using the basic idea from a related interview question you could do:

    • Sum up all the numbers (we shall call this S1) and their squares (S2)
    • Compute the expected sum of the numbers, without modifications, i.e. E1 = n*(n+1)/2 and E2 = n*(n+1)*(2n+1)/6
    • Now you know that E1 - S1 = d - m and E2 - S2 = d^2 - m^2, where d is the duplicated number and m the missing one.
    • Solve this system of equations and you'll find that:

      m = 1/2 ((E2 - S2)/(E1 - S1) - (E1 - S1))
      d = 1/2 ((E2 - S2)/(E1 - S1) + (E1 - S1)) // or even simpler: d = m + (E1 - S1)
      

    .

    $S1 = $S2 = 0;
    foreach ($nums as $num) {
        $S1 += $num;
        $S2 += $num * $num;
    }
    
    $D1 = $n * ($n + 1) / 2                - $S1;
    $D2 = $n * ($n + 1) * (2 * $n + 1) / 6 - $S2;
    
    $m = 1/2 * ($D2/$D1 - $D1);
    $d = 1/2 * ($D2/$D1 + $D1);
    

提交回复
热议问题