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?
分析:
每一个数都出现两次,只有一个数出现一次,其实我们可以知道两个相同的异或为0,0和任意的数异或为任意数,那么就可以知道,所有的异或之后就是只剩下那个只出现一次的数了
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
分析:
每一个数都出现两次,只有一个数出现一次,其实我们可以知道两个相同的异或为0,0和任意的数异或为任意数,那么就可以知道,所有的异或之后就是只剩下那个只出现一次的数了
所以代码实现就很简单了
public class SingleNumber {
public int singleNumber(int[] A) {
int result = 0;
for(int i=0;i<A.length;i++){
result ^= A[i];
}
return result;
}
}