一. 题目
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,剩下的就是所求的单独的数。
三. AC代码
public int singleNumber(int[] nums) {
int result=nums[0];
for(int i=1;i<nums.length;i++){
result=result^nums[i];
}
return result;
}