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?
最简单直接的方法,是使用一个 hashmap,记录每个数字出现的次数,最后遍历所有 entry,当发现次数为1的数字时,返回该数字。
这个方法时间复杂度 O(2n),空间复杂度 O(n),实际上,空间复杂度可以被减少。
这是一道非常好的学习 bit manipulate 的题目,我们会发现,xor 有着以下特征:
返回两个数的不同
比如 2(0010) 和 5(0101),结果将是 0111,每个数据不同的位将会设为1.
同时两个相同的数将返回0
利用这个特征
每个出现两次的数字都将最终被异或清零,留下一个 single number,如果我们将最早的异或数字设为0,因为0与任何数 xor 都会返回那个数本身。
public class Solution {
public int singleNumber(int[] nums) {
int num = 0;
for(int k:nums){
num ^= k;
}
return num;
}
}