给定一个整数数组 nums,其中恰好有两个元素只出现一次,其他所有元素均出现两次。 找出只出现一次的那两个元素。
示例:
给定 nums = [1, 2, 1, 3, 2, 5], 返回 [3, 5].
注意:
结果的顺序并不重要,对于上面的例子 [5, 3] 也是正确答案。
你的算法应该具有线性复杂度,你能否仅使用恒定的空间复杂度来实现它?
解题思路:
1.异或运算 因为a^a = 0
2.将数组分为两组
3.如3(011)^5(101)=6(110),证明,3和5的倒数第二位不同=> 3&2>0,5&2==0
class Solution {
public int[] singleNumber(int[] nums) {
int[] res = new int[2];//找打两个只出现一次的数
int temp = 0;
for (int i = 0; i < nums.length; i++) {
temp ^= nums[i];
}
int tm = (int) Math.pow(2, getLast1(temp));
res[0] = 0;
res[1] = 0;
for (int i = 0; i < nums.length; i++) {
//分为两组进行异或运算
if((nums[i]&tm)>0){
res[0] ^= nums[i];
}else{
res[1] ^= nums[i];
}
}
return res;
}
//找到最后一个1的位置
public static int getLast1(int n) {
if(n==0)
return -1;
int count = 0;
while(n!=0){
if((n&1)==1){
return count;
}else{
count++;
n = n>>1;
}
}
return count;
}
}