1. 题目
2. 思路
(1) 位运算
- 将所有数字进行异或运算,结果即为两个只出现一次的数字进行异或运算的结果。
- 找出该结果中任意一位值为1的二进制位,根据该二进制位,可以将所有数字分为两组,两个只出现一次的数字必定各在一组,其他数字必定两两出现在某一组。
- 分别对两组中所有数字进行异或运算,即可得到两个只出现一次的数字。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int[] FindNumsAppearOnce(int[] array) {
int[] res = new int[2];
int num = 0;
int n = array.length;
for (int i = 0; i < n; i++) {
num ^= array[i];
}
int bit = 1;
while (true) {
if ((bit & num) != 0) {
break;
}
bit <<= 1;
}
for (int i = 0; i < n; i++) {
if ((array[i] & bit) == 0) {
res[0] ^= array[i];
} else {
res[1] ^= array[i];
}
}
if (res[0] > res[1]) {
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
return res;
}
}