题目
给一组数,只有两个数只出现了一次,其他所有数都是成对出现的。怎么找出这两个数
思路
异或消除成对数据
代码
class Solution {
public void findTwoSingle(int[] nums) {
int ret = 0;
for (int i = 0; i < nums.length; i++) {
ret ^= nums[i];
}
int ret1 = 0, ret2 = 0;
int offset = 0;
int temp = 1;
while((num & temp) == 0){ //找到最右边一位1,然后分组异或
temp = temp<<1;
offset++;
}
for (int i = 0; i < nums.length; i++) {
int x = (nums[i] >> offset) % 2;
if (x == 1) {
ret1 ^= nums[i];
} else {
ret2 ^= nums[i];
}
}
System.out.println(ret1 + " " + ret2);
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 1, 2, 3, 3, 4, 4, 5, 6, 6};
solution.findTwoSingle(nums);
}
}