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?
思路分析:这题要求线性时间复杂度,需要用到位运算,X ^ X = 0,也就是任何数和自己取异或必然为0,于是这题我们可以把所有数组里的数取异或,最后剩下来的数就是那个只出现了一次的数。
AC Code:
public class Solution {
public int singleNumber(int[] A) {
int xorRes = 0;
for(int i = 0; i < A.length; i++){
xorRes = xorRes ^ A[i];
}
return xorRes;
}
}