Problem description: except two numbers in an integer array, the other numbers appear twice. Write a program to find the numbers that appear only once. The time complexity is O (n) and the space complexity is O (1 ).
Idea: if only one number appears only once, and the other two appear, you can directly perform an exclusive or operation on all numbers, because equal numbers are different or the result is 0. If two numbers appear only once, the other numbers appear twice. What should I do? The book "The beauty of programming" provides a method to first perform an exclusive or operation on all numbers to obtain a number, and then use a non-zero bit of the number as the filter bit, divide the array into two parts. The number that appears only once is divided into different parts. Now the problem occurs only once. You can perform an exclusive or operation on each part.
Reference code:
// Function: find two numbers that only appear once in the array // function parameter: arr is the source array, Len is the number of array elements, and result is used to store the result // return value: no void findisolatetwo (int * arr, int Len, int * result) {int I, all = 0, flag = 1; for (I = 0; I <Len; I ++) // All numbers are different or all ^ = arr [I]; while (! (ALL & flag) // search for the filter Bit Flag <= 1; Result [0] = Result [1] = 0; for (I = 0; I <Len; I ++) // use a filter bit to distinguish {If (flag & arr [I]) result [0] ^ = arr [I]; elseresult [1] ^ = arr [I] ;}}
I enjoy the copyright of blog articles, reprint please indicate the source http://blog.csdn.net/wuzhekai1985