Puzzle : finding out repeated element in an Array

后端 未结 9 1058
面向向阳花
面向向阳花 2021-02-10 17:39

Size of an array is n.All elements in the array are distinct in the range of [0 , n-1] except two elements.Find out repeated element without using extra temporary array with con

9条回答
  •  攒了一身酷
    2021-02-10 18:11

    XOR all the elements together, then XOR the result with XOR([0..n-1]).

    This gives you missing XOR repeat; since missing!=repeat, at least one bit is set in missing XOR repeat.

    Pick one of those set bits. Iterate over all the elements again, and only XOR elements with that bit set. Then iterate from 1 to n-1 and XOR those numbers that have that bit set.

    Now, the value is either the repeated value or the missing value. Scan the elements for that value. If you find it, it's the repeated element. Otherwise, it's the missing value so XOR it with missing XOR repeat.

提交回复
热议问题