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个。
本文介绍了一种在给定的2*n+1个数字中找到唯一出现一次的数字的方法。提供了两种解决方案:一种利用异或操作的特点实现高效查找;另一种通过排序后遍历数组来定位目标数字。
712

被折叠的 条评论
为什么被折叠?



