简体   繁体   English

XOR查找两个列表之间缺少的元素

[英]XOR to find the missing element between two lists

I try to solve this problem 我试图解决这个问题

"Consider an array of non-negative integers. A second array is formed by shuffling the elements of the first array and deleting a random element. Given these two arrays, find which element is missing in the second array." “考虑一个非负整数的数组。通过对第一个数组的元素进行混洗并删除一个随机元素来形成第二个数组。给定这两个数组,找出第二个数组中缺少哪个元素。”

And one of the solution is below code using XOR 解决方案之一是使用XOR的以下代码

def find(arr1, arr2): 
    result=0 

    # Perform an XOR between the numbers in the arrays
    for num in arr1+arr2: 
        result^=num 
        print result

    return result 


arr1 = [1,2,3,4,5,6,7]

arr2 = [3,7,2,1,4,6]

The result of the function is 5. 该函数的结果为5。

I know the basic principle of XOR. 我知道XOR的基本原理。 But I can't understand how the above code can find the result. 但是我不明白上面的代码如何找到结果。

Some important concepts: 一些重要的概念:

  1. XOR of a number with itself is always 0 数字与自身的XOR始终为0

  2. XOR of a number with 0 is always the number itself 数字与0的XOR始终是数字本身

  3. The order of an XOR operation is inconsequential XOR操作的顺序无关紧要

With this, consider: 为此,请考虑:

 1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 ^ 3 ^ 7 ^ 2 ^ 1 ^ 4 ^ 6 → (1 ^ 1) ^ (2 ^ 2) ^ (3 ^ 3) ^ (4 ^ 4) ^ (5) ^ (6 ^ 6) ^ (7 ^ 7) → 0 ^ 0 ^ 0 ^ 0 ^ 5 ^ 0 ^ 0 → 5 

And so, the odd one out remains. 因此,奇数仍然存在。

You start with the result = 0 您从结果= 0开始

Then you keep XORing the result with all the elements of each array. 然后,将结果与每个数组的所有元素进行XOR运算。 The XOR flips all the nonzero bits of the number you currently have. XOR翻转您当前拥有的数字的所有非零位。

So when you encounter the same number twice, you have flipped the same set of bits twice - meaning that you are back at the state you started with. 因此,当您两次遇到相同的数字时,您将相同的一组位翻转了两次-意味着您回到了开始时的状态。

Every number that appears in both lists ends up "canceling itself". 两个列表中出现的每个数字都以“取消自身”结尾。 The only number that is not canceled is the one that is missing from the second list. 唯一未取消的号码是第二个列表中缺少的号码。

It doesn't matter what each integer is - the bits will flip twice if the number appears twice, and once if the number appears once. 不管每个整数是什么-如果数字出现两次,位将翻转两次,如果数字出现一次,则位翻转一次。 It doesn't even matter if the number is missing in the first or the second array. 第一个数组或第二个数组中的数字是否丢失都没有关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM