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

后端 未结 8 1336
青春惊慌失措
青春惊慌失措 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:41

    If all numbers were present in the array the sum would be N(N+1)/2.

    Determine the actual sum by summing up all numbers in the array in O(n), let this be Sum(Actual).

    One number is missing, let this be j and one number is duplicated, let this be k. That means that

    Sum(Actual) = N(N+1)/2 + k - j

    derived from that

    k = Sum(Actual) -N(N+1)/2 + j

    Also we can calculate the sum of squares in the array, which would sum up to n3/3 + n2/2 + n/6 if all numbers were present.

    Now we can calculate the actual sum of squares in O(n), let this be Sum(Actual Squares).

    Sum(Actual Squares) =n3/3 + n2/2 + n/6 + k2 - j2

    Now we have two equations with which we can determine j and k.

提交回复
热议问题