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?
Solution
public int singleNumber(int[] nums) {
int re = 0;
for(int i=0; i< nums.length; i++ ){
re ^= nums[i];
}
return re;
}
这里使用异或的方法。 比如输入的数组是 {1, 2, 3, 4, 2, 3, 1}
re = 0^1^2^3^4^2^3^1
=0^(1^1)^(2^2)^(3^3)^4
=0^0^0^0^4
=0^4
=4