题目:
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?
这个题挺tricky的,想到了其实很简单。。一开始想了半天想用HashSet来做,但是貌似太啰嗦,后来发现异或简直是一步到位。
一个数异或自己就是0,把这个数组里的数全异或一次,剩下的就是那个只出现一次的了。
public class Solution {
public int singleNumber(int[] A) {
int theone=0;
for(int i=0;i<=A.length-1;i++){
theone=theone^A[i];
}
return theone^0;
}
}