In a shaped array of length n, the other numbers appear 2 times except that three digits appear only once. Please write the program output any one occurrence of the number, the program time and space complexity of the smaller the better. For example: a = {1,3,7,9,5,9,4,3,6,1,7}, output 4 or 5 or 6.
Thinking of solving problems
- If only one occurrence occurs only once, all the numbers are made in an XOR or operation, returning their values.
- If there are two numbers appearing only once, assuming A and B, the result of all the XOR operations is x=a^b, because A and B are unequal, so X is not 0. Scan from right to left for the first 1 bit, according to whether it is 1, divide the original array into two groups, and then treat each group of data according to the situation.
- For cases where three numbers occur only once, they can be solved according to three number 22 XOR, the lowest bit having two identical, and one difference .
Implementation code
#include <iostream>using namespace STD;intLowbit (intx);intFindint*num,intLen);intMain () {intNum[] = {1,1,2,2,3,3,4,4,5,6,7};cout<<find (NUM,sizeof(num)/sizeof(num[0])) <<endl;return 0;}//Find out where the first 1 appears from right to leftintLowbit (intx) {returnX & ~ (X-1);}intFindint*num,intLen) {intXORs =0; for(inti =0; i < Len; i++) {xors ^= num[i]; }//Three number 22 XOR, the lowest bit has two identical, there is a different intLow =0; for(inti =0; i < Len; i++) {//indicates low = Lowbit (a^b) ^ lowbit (a^c) ^ lowbit (b^c)Low ^= lowbit (xors ^ num[i]); }intresult =0; for(inti =0; i < Len; i++) {if(Lowbit (xors ^ num[i]) = = low) {result ^= num[i]; } }returnResult;}
[Xiaomi] shaped number