题解 | #数组中只出现一次的两个数字#
数组中只出现一次的两个数字
https://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce (int[] array) {
// write code here
int n = array.length;
//异或:相同为0,不同为1 ^
//对array数组各元素异或,得出(两个不同元素)的异或值[相同的元素异或得0]
int t = 0; //任何数异或0都为这个任何数
for (int i = 0; i < n; i++) {
t = t ^ array[i];
}
//寻找可以分组去进行与运算的数
//eg:1010 -> 0010
int m = 1;
while(((t & m) == 0)) { //eg:1010 & 0001 = 0 这(两个不同的元素)在这个位置相同,不能
//进行分组故继续循环[要把这两个不同的元素分到不同的两组中]
m <<= 1; //左移一位 eg:0001 -> 0010
}
//eg:1010 -> 0010时 根据第一个1所在位置的不同分成两组即根据&0010分成两组
//array数组根据&0010所得结果不同可被分为两组
//两个不同的组异或结果就是a和b
int a = 0;
int b = 0;
for (int i = 0; i < n; i++) {
if ((m & array[i]) == 0) { //通过7运算结果是否为0分辨这两个组
a ^= array[i]; //异或的a
} else {
b ^= array[i]; //异或的b
}
}
//输出时按非降序排列故判断a,b大小
if (a > b) {
t = a;
a = b;
b = t;
}
int[] x = {a, b};
return x;
}
}
嘉士伯公司氛围 714人发布
查看5道真题和解析