题目
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory
经典的方法就是从头到尾的异或运算,这里说不要用额外空间,那么可以直接用数组元素存储计算结果。
扩展的方法可以参考Single Number II中的解法。
代码
public class SingleNumber {
public int singleNumber(int[] A) {
assert A != null && A.length > 0;
for (int i = 1; i < A.length; ++i) {
A[0] ^= A[i];
}
return A[0];
}
}