题目:
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear run time complexity. Could you implement it without using extra memory?
分析:
这道题既用线性的时间复杂度也不用额外的存储空间,使用一个技巧,位异或。如果数是成对出现的,那么它们的异或结果是0,而任何数和0按位异或的结果是它本身。走一趟最后所有数的异或结果就是这个单独出现的数。
Java代码实现:
public class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for(int i=0;i<nums.length;i++)
result = result ^ nums[i];
return result;
}
}