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

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

    Taking the leave the array untouched requirement literally (i.e. the array can be temporarily modified as long as it does not change in the end), a programming-oriented solution can be suggested.

    I assume that array size N is much smaller than 2^64 which is an utterly unrealistic amount of memory. So we can safely assume that N < 2^P such that P << 64 (significantly smaller). In other words this means that all numbers in the array have some high bits unused. So let's just use the highest bit as a flag whether the index of that position has been seen in the array. The algorithm goes as follows:

     set HIGH = 2^63  // a number with only the highest bit set
     scan the array, for each number k do
       if array[k] < HIGH: array[k] = array[k] + HIGH // set the highest bit
       else: k is the duplicate
     for each i in 1..N do
       if array[i] < HIGH: i is missing
       else: array[i] = array[i] - HIGH // restore the original number
    

    This is linear time and very little computation

提交回复
热议问题