Single Number:
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?
题目要求:一个数组中除了一个元素每个元素都出现了两次,找到那个出现了一次的元素。
并且要求空间复杂度:O(1)
解题思路:
这里我们考虑使用异或来解决问题,首先我们先说一下异或的知识。
异或(xor)是一个数学运算符。它应用于逻辑运算。异或符号为“^”。基本运算法则为:
1.a^b=b^a
2.a^b^c=(a^b)^c=a^(b^c)
3.a^a=0
4.b^0=b
所以我们运用这样的性质来解决这个问题。
例:
数组为:1231434,除了2其他1,3,4都出现了两次,我们从数组第一个开始
1^2=1^2
1^2^3=1^2^3
1^2^3^1=1^1^2^3=0^2^3=2^3
2^3^4=2^3^4
2^3^4^3=2^4^3^3=2^4^0=2^4
2^4^4=2^0=2
得解:2
Solution:
public class Solution {
public int singleNumber(int[] A) {
if(A==null||A.length=0)
{
return 0;
}
int result= A[0];
int i;
for(i=1;i<A.length;i++)
{
result=result^A[i];
}
return result;
}
}