Given 2*n + 1 numbers, every numbers occurs twice except one, find it.
Example
Given [1,2,2,1,3,4,3], return 4
异或:
public int singleNumber(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
int n = A[0];
for (int i = 1; i < A.length; i++) {
n = n ^ A[i];
}
return n;
}
排序:
public int singleNumber(int[] A) {
if (A.length == 0) {
return 0;
}
Arrays.sort(A);
int i = 0;
while (i < A.length - 1) {
if (A[i] == A[i + 1]) {
i += 2;
} else {
break;
}
}
return A[i];
}
思路:
1. 异或相同的数会抵消
2. 有序排列,相等的数相邻,一次跳2个。