一、請問在一個數組裏除了某一個數字之外,其他的數字都出現了兩次。如何找出落單的那個數?
答:用輔助數組法,元素轉下標,下標轉元素。輔助數組對原數組元素進行計數,數組元素爲1,則下標爲落單的那個數。
用異或消除法。因爲0^A=A,A^A=0。
import java.util.Arrays;
public class 題2_找出落單的那個數 {
static int arr[]= {2,8,6,3,6,9,2,8,9};
static int helper[]=new int[10];
public static void main(String[] args) {
//輸出原數組
System.out.println(Arrays.toString(arr));
//輔助數組法
helperArr();
//異或消除法
yihuoArr();
}
//異或消除法
private static void yihuoArr() {
int x=0;
for(int i=0;i<arr.length;i++) {
x=x^arr[i];
}
System.out.println(x);
}
//輔助數組法
private static void helperArr() {
for(int i=0;i<arr.length;i++) {
helper[arr[i]]++; //數組轉下標
}
for(int i=0;i<arr.length;i++) {
if(helper[i]==1) { //下標轉元素
System.out.println(i);
}
}
}
}