題目:一個整型數(shù)組里除了兩個數(shù)字之外饭入,其他的數(shù)字都出現(xiàn)了兩次各吨,請寫程序找出這兩個只出現(xiàn)一次的數(shù)字排苍。要求時間復雜度是O(n)沦寂,空間復雜度是O(1)。
代碼如下:
package demo;
/**
* 數(shù)組中只出現(xiàn)一次的數(shù)字
*
* @author xiangdonglee
*
*/
public class Test40 {
public static int[] findNumbersAppearanceOnce(int[] data) {
int[] result = { 0, 0 };
if (data == null || data.length < 2) {
return result;
}
int resultExclusiveOR = 0;
for (int i : data) {
resultExclusiveOR ^= i;
}
int indexOf1 = findFirstBit1(resultExclusiveOR);
for (int i : data) {
if (isBit1(i, indexOf1)) {
result[0] ^= i;
} else {
result[1] ^= i;
}
}
return result;
}
/**
* 在整數(shù)num的二進制表示中找到最右邊是1的位
*
* @param num
* @return
*/
private static int findFirstBit1(int num) {
int index = 0;
while ((num & 1) == 0 && index < 32) {
num >>>= 1;
index++;
}
return index;
}
/**
* 判斷在整數(shù)num的二進制表示中淘衙,從右邊數(shù)起的indexBit位是不是1
*
* @param num
* @param indexBit
* @return
*/
private static boolean isBit1(int num, int indexBit) {
num >>>= indexBit;
return (num & 1) == 1;
}
public static void main(String[] args) {
int[] data1 = { 2, 4, 3, 6, 3, 2, 5, 5 };
int[] result1 = findNumbersAppearanceOnce(data1);
System.out.println(result1[0] + " " + result1[1]);
int[] data2 = { 4, 6 };
int[] result2 = findNumbersAppearanceOnce(data2);
System.out.println(result2[0] + " " + result2[1]);
int[] data3 = { 4, 6, 1, 1, 1, 1 };
int[] result3 = findNumbersAppearanceOnce(data3);
System.out.println(result3[0] + " " + result3[1]);
}
}