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. Required time complexity is O (n), spatial complexity is O (1)
From beginning to end, or every number in an array, the result is an XOR result of two occurrences of a single number. Because the other numbers appear two times, they all cancel out in the XOR. Since these two numbers are definitely different, the XOR result is definitely not 0, meaning that at least one of the binary representations of the result number is 1. We find the position of the first 1 bit in the result number, which is recorded as the nth bit. Now we divide the numbers in the original array into two sub-arrays with the nth bit not 1, and the nth bit for each number in the first Subarray is 1, and the nth bit for each number of the second subarray is 0.
Now that we have divided the original array into two sub-arrays, each sub-array contains a single occurrence of the number, while the other numbers appear two times.
The key to the code is: 1. The illegal condition is length < 2 2. Indexbit < 8 * sizeof (int) is at most 31st bit 1
1UnsignedintFINDFIRSTBITIS1 (intnum);2 BOOLIsBit1 (intNum, unsignedintindexbit);3 4 voidFindnumsappearonce (intData[],intLengthint* NUM1,int*num2)5 {6 if(data = NULL | | length <2)7 return;8 9 intResultexclusiveor =0;Ten for(inti =0; i < length; ++i) OneResultexclusiveor ^=Data[i]; A -UnsignedintINDEXOF1 =FindFirstBitIs1 (RESULTEXCLUSIVEOR); - the*NUM1 = *num2 =0; - for(intj =0; J < length; ++j) - { - if(IsBit1 (Data[j], indexOf1)) +*num1 ^=Data[j]; - Else +*num2 ^=Data[j]; A } at } - - //Find num from the right number first is a bit of 1 -UnsignedintFINDFIRSTBITIS1 (intnum) - { - intIndexbit =0; in while(Num &1) ==0) && (Indexbit <8*sizeof(int))) - { tonum = num >>1; +++Indexbit; - } the * returnIndexbit; $ }Panax Notoginseng - //determine if the digit indexbit digit num is 1 the BOOLIsBit1 (intNum, unsignedintindexbit) + { Anum = num >>Indexbit; the return(Num &1); +}
Interview 40: Numbers that appear only once in an array