Q: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?
思路:一个整数异或它本身,结果为0. 所以只要遍历一次数组即可得到只出现一次的数字.
代码:
public int singleNumber(int[] nums) {
int length = nums.length, i = 0;
long sum = 0L;
while (i < length) {
sum ^= nums[i++];
}
return (int) sum;
}