【Question】
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?
题目:一个数组中,出了一个元素只出现一次,其他的元素都出现两次。
思想:由于一个数和它相等数异或为零,所以将这个数组的元素逐个异或,最后只会剩下出现一次的那个数
public class Solution {
public int singleNumber(int[] nums) {
int len =nums.length;
if (len==0) return 0;
int temp=nums[0];
for(int i=1;i<len;i++)
temp^=nums[i];
return temp;
}
}