Turn from: http://blog.csdn.net/newhappy2008/article/details/6857098
Question: There are n+2 number, n number appeared even several times, 2 numbers appear odd several times (these two numbers are not equal), ask the space complexity of O (1), find out these two numbers, do not need to know the exact location, just need to know these two values.
Solution: If only one number appears in the odd number of times, this is a better solution, directly to the array of elements of the different or different, or the result
Is the number that has only been in the odd number of times.
But there are 2 numbers in the title that appear odd several times. , the solution method is as follows:
Assuming that these two numbers are a,b, the x=a^b of all elements in the array, or the result, is judged by the number of digits in X with a bit of 1 (note: because A. =b, so x. =0, we just need to know the number of digits K of a bit 1, for example, 0010 1100, we would like to k=2 or 3, or 5, and then the X and the array of K-bit 1 of the number of different or, or the result is one of the a,b, and then with X or, you can find another.
Why, then? Because the K-bit in X is 1 means that the number of k in A or B is 1, assuming a, when X is different from the number of K-bits in the array, and the number of occurrences of x and a plus other K-bits of 1 is different or, the reduction is x and a, and the result is B.
code as follows: View plain Void getnum (int a[],int length) { & nbsp; int s=0;//Save XOR for (int i=0;i<length;i + +) { s=s^a[i]; } int temp1=s;//Temporary preservation of different or results int temp2=s;//temporary preservation of different or results int k=0; while ( TEMP1&1)//bit to 1 digits { temp1=temp1>>1; k++; } for (int i=0;i<length;i++) { &nbsP; if ((a[i]>>k) &1)// of S with the number k in the array is 1 { cout<<a[i] << " "; s=s^a[i];