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?
翻译:
给定一个整数数组,除了一个数只出现过一次,剩下的都出现过两次。请找出那个单独数字。
要求:线性时间复杂度,不能使用附加内存。
分析:抛开要求,此题很容易搞定,用过map统计出现次数。不过要命的是,空间复杂度。
如果学过逻辑运算的话,会发现一个很好玩的东东,比如一个整数,例如3,我们发现 3 xor 3 = 0, 3 xor 0 = 3.
更具这个观察,很容易发现解题方法,遍历列表,让0 xor列表中得所有值得到的最后结果就是所要求解的。
public class Solution {
public int singleNumber(int[] A) {
int rvl = 0;
for (int i = 0; i < A.length; i++){
rvl ^= A[i];
}
return rvl;
}
}