首先:位運算中異或的性質:兩個相同數字異或=0,一個數和0異或還是它本身。
當只有一個數出現一次時,我們把數組中所有的數,依次異或運算,最後剩下的就是落單的數,因爲成對兒出現的都抵消了。
依照這個思路,我們來看兩個數(我們假設是AB)出現一次的數組。我們首先還是先異或,剩下的數字肯定是A、B異或的結果,這個結果的二進制中的1,表現的是A和B的不同的位。我們就取第一個1所在的位數,假設是第3位,接着把原數組分成兩組,分組標準是第3位是否爲1。如此,相同的數肯定在一個組,因爲相同數字所有位都相同,而不同的數,肯定不在一組。然後把這兩個組按照最開始的思路,依次異或,剩餘的兩個結果就是這兩個只出現一次的數字。
public class Solution {
public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
int length = array.length;
if(length == 2){
num1[0] = array[0];
num2[0] = array[1];
return;
}
int bitResult = 0;
for(int i = 0; i < length; ++i){
bitResult ^= array[i];
}
int index = findFirst1(bitResult);
for(int i = 0; i < length; ++i){
if(isBit1(array[i], index)){
num1[0] ^= array[i];
}else{
num2[0] ^= array[i];
}
}
}
private int findFirst1(int bitResult){
int index = 0;
while(((bitResult & 1) == 0) && index < 32){
bitResult >>= 1;
index++;
}
return index;
}
private boolean isBit1(int target, int index){
return ((target >> index) & 1) == 1;
}
}
牛客網鏈接地址:https://www.nowcoder.com/profile/777651/codeBookDetail?submissionId=1504048