在重复元素XOR运算符的数组中找到两个非重复元素?

问题描述:

假设我有一个包含2n + 2个元素的数组。数组中的n个元素出现两次,其余两个元素是唯一的。您必须在O(n)时间和O(1)空间中解决此问题。解决方案之一是使用XOR。但是我不明白这一点。有人可以帮我解决这个问题还是可以给我更好的解决方案?

Suppose I have an array with 2n+2 elements. n elements in array are occurring twice and remaining two elements are unique. You have to solve this in O(n) time and O(1) space. One of the solution is using XOR. But I am not able to understand that. Can anyone help me regarding that or can give me better solution ?

问题与解决方案的链接是

Link of the Problem and solution is this

首先-请注意 a xor a == 0 ,对于每个 a

First - note that a xor a == 0, for each a.

假设您有两个唯一的数字- x,y

Let's say you have two unique numbers - x,y.

如果对每个元素进行异或运算,最终将得到一个单个数字,等于 x或y (因为每个重复对都将自身无效),并且至少有一个向上位。选择该位(如果多于一个,就不要选择哪个位),然后将列表分为两个子列表:

(1)设置了该位的所有数字。

(2)所有未设置此位的数字。

If you do xor on each element, you end up with a single number, which equals x xor y (because each dupe pair nullify itself), and has at least one bit "up". Chose this bit (Doesn't matter which up bit you take if there are more then one), and split the list into two sub lists:
(1) All numbers that have this bit set.
(2) all numbers that have this bit unset.

其中一个唯一数字具有此位,另一个不具有此位(否则-首先不是向上),因此每个列表中都有一个唯一的数字。

One of the unique numbers has this bit, the other does not (otherwise - it was not "up" in the first place), so you have one unique number in each list.

再次迭代每个列表,并对所有元素进行异或运算,结果是该列表中的唯一数字,因为每个重复的对都会使自身无效。

Iterate each list once more, and do xor on all elements, the result is the unique number in this list, since each duplicate pair nullify itself.