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?
采用异或的方式,因为
- 101^101 = 0 -> N^N = 0
- 101^000 = 101 -> N^0 = N
class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for(int n : nums)
res ^= n;
return res;
}
}