题目描述
现在有一个整数类型的数组,数组中素只有一个元素只出现一次,其余的元素都出现两次。
注意:
你需要给出一个线性时间复杂度的算法,你能在不使用额外内存空间的情况下解决这个问题么?
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?
思路:
通过异或^运算符来找到唯一的数,异或是一个数学运算符,用于逻辑运算。异或的数学符号为“⊕”,计算机符号为“xor”
当a=b时,a⊕b=0,当a!=b时,a⊕b=1
异或^(xor)的运算规律:
1. 0^x = x; x为任意数
2. a^b = b^a
3. a^(b^c) = (a^b)^c
4. a^b^a = a
代码如下所示:
public class Solution {
public int singleNumber(int[] A) {
int result = A[0];
//从头开始进行异或运算,运算到最后就会得到只出现一次的数
for(int i=1;i<A.length;i++){
result^=A[i];
}
return result;
}
}