/* 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); //xor&(-xor) or 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*/
}
}
http://www.geeksforgeeks.org/find-two-non-repeating-elements-in-an-array-of-repeating-elements/
有N个数,其中2个数出现了奇数次(这两个数不相等),其他数都出现偶数次,问用O(1)的空间复杂度,找出这两个数,不需要知道具体位置,只需要知道这两个值。
本文介绍了一种算法,该算法通过计算异或(xor)来找出包含重复元素的数组中的两个非重复数。首先计算整个数组的异或值,然后找出异或结果中最右侧的设置位,接着将数组分为两组并分别计算每组的异或值,最终得到两个非重复数。

被折叠的 条评论
为什么被折叠?



