Description: 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?
这是整个LeetCode上面做的第一道题。没啥好说的,XOR即可。
public class Solution {
public int singleNumber(int[] A) {
int single = 0;
for(int i=0; i < A.length; i++) {
single ^= A[i];
}
return single;
}
}
Assuming you can XOR
the numbers, that is the key here, I believe, because of the following properties:
-
XOR
is commutative and associative (so the order in which it's done is irrelevant). - a number
XOR
ed with itself will always be zero. - zero
XOR
ed with a number will be that number.
So, if you simply XOR
all the values together, all of the ones that occur twice will cancel each other out (giving 0) and the one remaining number (n
) will XOR
with that result (0) to give n
.