Title: In an integer array, except for two digits, the other numbers appear two times. Please write the program to find the two only occurrences of the number. The required time complexity is O (n), and the spatial complexity is O (1).
Or understanding is not deep enough.
The main idea of the problem is the pattern of numbers that appear once in an array, one-time traversal plus an XOR operation. Then this XOR value is definitely the difference or value of the two occurrences of the number. The result of 1 of the binary representation of this value indicates that the two numbers are different on that bit. So by doing this, we can separate the two occurrences of the number from the entire array with this bit.
By doing this, other two-time numbers will be divided into the same group, so the result is that there are two sets of data, each of which is an odd number of numbers, with only one occurrence.
#include <stdio.h>#include <assert.h>intFindouttwo (int*a,intNint&x,int&y) {assert (a); ASSERT (n>2);intresult=a[0]; for(intI=1; i<n;++i) Result^=a[i];intb=result&-result; x=0; y=0; for(intI=0; i<n;++i) {if(B&a[i]) x^=a[i];ElseY^=a[i]; }return 0;}intMain () {inta[]={1,1,2,2,3,3,4,4,5,6};intx, y; Findouttwo (A,sizeof(a)/sizeof(int), x, y);printf("%d%d\n", x, y); GetChar ();return 0;}
The result is:
Find two occurrences of a number in an array