题目描述:
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]
.
思考:
跟出现一次只有一个数那到题稍微难一些,出现一次,直接每一个异或运算即可,但是这里每一个异或运算后,得到的只是两个的异或运算结果,思路就是取两个数字的从低位到高位第一个不同的二进制位,也就是下面的result & (~(result-1));,这样就可以区分了,这样以这个数为底的和每一个数与运算,出现两次的自然会使用异或运算为0,或两个数字的与运算要嘛为0要嘛不为0。
代码:
public class SingleNumber_III {
public int[] singleNumber(int[] nums) {
int[] res = new int[2];
int result = nums[0];
for(int i=1;i<nums.length;i++){
result = result^nums[i];
}
res[0] = 0;
res[1] = 0;
int n = result & (~(result-1));
for(int i=0;i<nums.length;i++){
if((n & nums[i])!=0){
res[0] = res[0] ^ nums[i];
}else {
res[1] = res[1] ^ nums[i];
}
}
return res;
}
}