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

后端 未结 8 1274
青春惊慌失措
青春惊慌失措 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:48
        long long int len = A.size();
        long long int sumOfN = (len * (len+1) ) /2, sumOfNsq = (len * (len +1) *(2*len +1) )/6;
        long long int missingNumber1=0, missingNumber2=0;
    
        for(int i=0;i<A.size(); i++){
           sumOfN -= (long long int)A[i];
           sumOfNsq -= (long long int)A[i]*(long long int)A[i];
        }
    
        missingno = (sumOfN + sumOfNsq/sumOfN)/2;
        reaptingNO = missingNumber1 - sumOfN;
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题