有N个数,其中2个数出现了奇数次(这两个数不相等),其他数都出现偶数次,问用O(1)的空间复杂度,找出这两个数,不需要知道具体位置,只需要知道这两个值。

/* 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)的空间复杂度,找出这两个数,不需要知道具体位置,只需要知道这两个值。)