Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
本题初看可以使用hashmap,我的代码如下:
public class Solution {
public int[] singleNumber(int[] nums) {
HashMap hashmap = new HashMap();
for ( int i =0 ;i<nums.length;i++) {
if (hashmap.containsKey(nums[i])) hashmap.remove(nums[i]);
else hashmap.put(nums[i],i);
}
Iterator it = hashmap.keySet().iterator();
int ans[] = new int[2];
int x = 0;
while (it.hasNext()) {
ans[x] = (int)it.next();
x++;
}
return ans;
}
}
但在经过看discuss后,发现可以使用XOR(^)来进行计算
如果一组数里面有两个单个数,那么XOR的结果一定是这两个数的XOR,这个结果中的每个二进制下的1都是两个数不同的地方,而其他数会在XOR运算中抵消掉。那么可以针对第一个结果中的1进行分类,多余的两个不同的数一定有一个是1而另一个是0,又因为其他数都会抵消掉,那么可以对这个位进行判断后进行XOR。