Title: In an integer array, except for two digits, the other numbers appear two times. Please write out the program to find the two only occurrences of the number. The time complexity required is O (n) and the spatial complexity is O (1).
All two of these topics emphasize that one (or two) numbers appear only once and others appear two times. What's the point? We think of a nature of the XOR operation: any one number XOR itself equals 0. That is, if we question every number in the array from beginning to end, then the final result is exactly the one that appears only once, because those numbers that have been paired two times are all offset by XOR.
After trying to figure out how to solve this simple problem, let's go back to the original question and see if we can use the same ideas. We try to divide the original array into two sub-arrays, so that each sub-array contains a number that appears only once, while the other numbers appear in pairs two times. If we can split the two arrays in this way, we can find out two numbers that appear only once in the previous way.
Ideas:
1, first of all different or itself, to find the final result.
2, according to the results to find out the position of 1.
3, depending on whether the corresponding position in the array contains 1 of the different or array of decisions.
Public classonetocount{ Public voidGetCount (int[] Array) { if(array==NULL|| ARRAY.LENGTH<2)return ; intYihuo=array[0]; for(inti=1;i<array.length;i++) {Yihuo^=Array[i]; } intresult =getonebit (Yihuo); intNum1=0; intNum2=0; for(inti=0;i<array.length;i++){ if(Isonebit (Array[i],result)!=0) num1 ^=Array[i]; ElseNum2 ^=Array[i]; } System.out.println (NUM1); System.out.println (NUM2); } Public intGetonebit (intN) { intCount =0; while((n&1) ==0){ ++count; N=n>>1; } returncount; } Public intIsonebit (intNintm) {N= n>>m; return(n&1); } Public Static voidMain (string[] args) {onetocount o=NewOnetocount (); int[] Array = {2,4,3,6,3,2,5,5}; O.getcount (array); }}
A number that appears only once in an array