【发布时间】:2014-05-22 01:42:08
【问题描述】:
给定[1,1,4,5,5,6],我们可以找到4 和6 是不重复的整数。
有一个solution 使用XOR。
这是作者提出的算法:
#include <stdio.h>
#include <stdlib.h>
/* This finction sets the values of *x and *y to nonr-epeating
elements in an array arr[] of size n*/
void get2NonRepeatingNos(int arr[], int n, int *x, int *y)
{
int xor = arr[0]; /* Will hold xor of all elements */
int set_bit_no; /* Will have only single set bit of xor */
int i;
*x = 0;
*y = 0;
/* Get the xor of all elements */
for(i = 1; i < n; i++)
xor ^= arr[i];
/* Get the rightmost set bit in set_bit_no */
set_bit_no = xor & ~(xor-1);
/* Now divide elements in two sets by comparing rightmost set
bit of xor with bit at same position in each element. */
for(i = 0; i < n; i++)
{
if(arr[i] & set_bit_no)
*x = *x ^ arr[i]; /*XOR of first set */
else
*y = *y ^ arr[i]; /*XOR of second set*/
}
}
我对@987654328@ 之后的内容感到困惑。我很困惑set_bit_no 是如何工作的(包括动机)以及之后的任何事情。
有人可以尝试用更简单的英语方式来解释它吗?谢谢。
【问题讨论】:
-
如果在 xor 中设置的第一个位在位置 k,那么所有高于 k 的位在 xor 和 ~(xor-1) 中都会不同,导致零位和所有位在更低的位置比 k 在 xor 和 ~(xor - 1) 中都为零,结果为零。只有位置 k 的位会在两者中设置,从而导致 set_bit_no 的值正确。有关更多详细信息,请查看我的答案。
-
您应该已经解释了数字是成对出现的,但其中两个是成对出现的。
-
重复this