only one number appears once in an array, and the other numbers appear two times, how do you find the number that appears once? For example, array a[11]={1,2,2,3,3,4,4,5,5,6,6}, the occurrence is 1, through the XOR algorithm can be obtained.
The code is as follows:
int onediffent (int a[],int n) {int temp=0;for (int i=0;i<n;i++) temp=temp^a[i];p rintf ("%d\n", temp);}
Supplement: Any number with 0 XOR or equal to any number. Any number differs from oneself or is 0;
If the problem turns into an array with two numbers appearing once and the other numbers appearing two times, how do you find the two numbers?
Algorithm idea: First, the array of a set of numbers XOR, the result exists in temp, and then calculate the location of the lowest bit in the temp, and then all the numbers in the group and so on, so that the array is divided into two arrays, the problem is converted to an array of only one number occurrences of the case.
The code is as follows:
int twodiffent (int a[],int n) {int temp,count,i,j,k;temp=a[0];j=k=0;int b[n],c[n];for (int i=1;i<n;i++) temp=temp^a[ i];count=1;//find the lowest bit position in temp 1 while (!) temp&1)) {temp=temp>>1;count*=2;} Divide two numbers into two arrays, and the problem is converted to only one occurrence of the number in an array. for (i=0;i<n;i++) {if (a[i]&count==1) b[j++]=a[i];elsec[k++]=a[i];} Onediffent (B,J); onediffent (c,k);}
in the algorithm group, an enthusiastic netizen to get the current optimal solution, relative to the algorithm two optimized for at least a century <, the code is as follows:
void Solve (int num[],int n) { int x = 0; for (int i = 0; i < n; ++i) { x = x ^ num[i]; } int smallestone = x &-X; int a = 0; int b = 0; for (int i = 0; i < n; ++i) { if ((Num[i] & smallestone)! = 0) A = a ^ num[i]; else B = b ^ num[i]; } printf ("%d%d\n", A, b);}
The algorithm in the x&-x is the lowest bit of 1, negative numbers in the computer is a complement, for example 4&-4=4,1000&-1000=8 represents the number 4 bits 1 the lowest bit is in the right to 2^2 appear, the number 10,002 binary bit 1 is the lowest bit in the weight of 2^ 3 appears. The array in algorithm two is completely unnecessary, the space complexity is O (1), the time complexity O (n);
If you have a better way, you might as well discuss it here.
Find the number that appears once in the array