Problem description
An integer array in addition to two digits, the other numbers appear even several times. Please write the program to find the two only occurrences of the number.
Thinking of solving problems
If only one number in the array appears odd times, all the numbers in the array will be different or available for that number.
There are two numbers in the array that appear odd number of times, set the two numbers are a, B, then all the numbers in the array will be different or get a and B xor result, set to XOR.
The number a differs from B in that there is at least 1 bits in the binary representation of A and B, and the bit of 1 in the XOR binary representation is a different bit from B, assuming that a is different from the K-bit of B, where a is 1,b on that bit for 0. (k can be selected as the first distinct bit starting from the starting bit)
You can divide the array into two words according to the value of the number k bit, and the sub-array with the K-bit 1 must contain a and other occurrences of the number (the same number is the same as the K-bit), and the sub-array with the K-bit 0 must contain B and other numbers that appear even several times.
The numbers in the subarray are different or the numbers a and B can be obtained separately.
Implementation code
//The num1,num2 are arrays of length 1, respectively. Outgoing Parameters//set Num1[0],num2[0] to return the result Public voidFindnumsappearonce (int[] Array,intNum1[],intnum2[]) { //get the XOR of two numbers or results intXOR = 0; for(inti=0; i<array.length; i++) XOR ^=Array[i]; //ask for two digits first different bit with temp record//If temp=00100000 indicates that the 6th digit of two digits is different inttemp = 1; while(XOR & 1)! = 1) {Temp= Temp << 1; XOR= XOR >> 1; } //divides the array into two sub-arrays according to temp, and makes separate orNum1[0] = 0; num2[0] = 0; for(inti=0; i<array.length; i++) if((array[i]&temp) = = temp) num1[0] ^=Array[i]; ElseNum2[0] ^=Array[i]; }
Numbers that appear only once in an array (Java implementation)