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?
给定一组整数,出了一个数外其他整数全部都出现了两次。
Note:
你的算法必须是线性的时间复杂度,你能不用额外的空间的么?
方法很简单,运用异或运算。
异或运算满足交换律,当两数相同时为0,不同时为1。所以所有有两个的数异或之后都为0了,最后再跟最后一个single异或则得到那个single。
代码如下:
class Solution {
public:
int singleNumber(int A[], int n) {
int result=0;
for(int i=0;i<n;i++)
{
result=result^A[i];
}
return result;
}
};