题目描述
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
X^0=1
Java的异或(^)运算:两个操作数的位中,相同则结果为0,不同则结果为1。
一个数和0异或还是自己,一个数和自己异或是0。(0 ^ N = N, N ^ N = 0)
假定有2K+1个数,其中有2k个相同,需要找出不相同的那个数,可以利用异或运算符。
N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N
= (N1^N1) ^ (N2^N2) … (Nx^Nx) ^ N
= 0 ^ 0 ^ …^ 0 ^ N
= N
public class Solution {
public int singleNumber(int[] A) {
int res=A[0];//取第一个数
for(int i=1;i<A.length;i++){
res=res^A[i];//从第二个数开始,遍历每个数进行异或
}
return res;
}
}