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?
一个数组里每个数都出现两次,除了一个数只出现一次。想要找出这个只出现过一次的数,用异或^符可以轻松找到,代码如下:
public class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
result ^= nums[i];
}
return result;
}
}