Using XOR operator for finding duplicate elements in a array fails in many cases

前端 未结 6 1984
野的像风
野的像风 2021-02-01 10:36

I came across a post How to find a duplicate element in an array of shuffled consecutive integers? but later realized that this fails for many input.

For ex:
a

6条回答
  •  遇见更好的自我
    2021-02-01 11:08

    From original question:

    Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array, except for one number, which occurs twice.

    It basically says, that algorithm only works when you have consecutive integers, starting with 1, ending with some N.

    If you want to modify it to more general case, you have to do following things:

    Find minimum and maximum in array. Then calculate expected output (xor all integers between minimum and maximum). Then calculate xor of all elements in array. Then xor this two things and you get an output.

提交回复
热议问题