[Xiaomi] ry number, ry number
In an integer array a with a length of n, all the other numbers appear twice except three digits. Write a program to output any number that appears only once. The smaller the time and space complexity of the program, the better. Example: a = {, 7}, output 4, 5, or 6.
Solutions
- If only one occurrence occurs once, all the numbers are converted into an exclusive or operation and their values are returned.
- If two numbers appear only once, for example, a and B, the result of an exclusive or operation on all numbers is x = a ^ B. Because a and B are not equal, x is not 0. Scan the first digit of 1 from the right to the left, and divide the original array into two groups based on whether the value is 1, and then process each group of data as needed.
- If there are three numbers only once, you canThe three numbers are two-to-one or different, And the bitwise has two identical values..
Implementation Code
# Include <iostream> using namespace std; int lowbit (int x); int find (int * num, int len); int main () {int num [] = {1, 1, 2, 2, 3, 3, 4, 5, 6, 7}; cout <find (num, sizeof (num)/sizeof (num [0]) <endl; return 0 ;} // find the first position from right to left where 1 appears, int lowbit (int x) {return x &~ (X-1);} int find (int * num, int len) {int xors = 0; for (int I = 0; I <len; I ++) {xors ^ = num [I];} // The three numbers are two or two different, And the bitwise has two identical values, one different int low = 0; for (int I = 0; I <len; I ++) {// indicates low = lowbit (a ^ B) ^ lowbit (a ^ c) ^ lowbit (B ^ c) low ^ = lowbit (xors ^ num [I]);} int result = 0; for (int I = 0; I <len; I ++) {if (lowbit (xors ^ num [I]) = low) {result ^ = num [I] ;}} return result ;}