Find the two non-repeating elements in an array of repeating element XOR operator?

筅森魡賤 提交于 2019-12-07 05:18:29

问题


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


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/11843418/find-the-two-non-repeating-elements-in-an-array-of-repeating-element-xor-operato

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!