Given numbers from 1 to 2^32-1, one is missing. How to find the missing number optimally?

前端 未结 5 1052
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 03:58

You are given 2^32-2 unique numbers that range from 1 to 2^32-1. It\'s impossible to fit all the numbers into memory (thus sorting is not an option). You are asked to find t

5条回答
  •  失恋的感觉
    2020-12-14 05:01

    Use bitwise operator XOR. Here are example in JavaScript:

    var numbers = [6, 2, 4, 5, 7, 1]; //2^3 exclude one, starting from 1
    var result = 0;
    
    //xor all values in numbers
    for (var i = 0, l = numbers.length; i < l; i++) {
        result ^= numbers[i]; 
    }
    
    console.log(result); //3
    
    numbers[0] = 3; //replace 6 with 3
    //same as above in functional style
    result = numbers.reduce(function (previousValue, currentValue, index, array) {return currentValue ^= previousValue;});
    
    console.log(result); //6
    

    The same in C#:

    int[] numbers = {3, 2, 4, 5, 7, 1};
    
    int missing = numbers.Aggregate((result, next) => result ^ next);
    
    Console.WriteLine(missing);
    

提交回复
热议问题