题解 | #数组中只出现一次的两个数字#
数组中只出现一次的两个数字
https://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce (int[] array) {
int[] res = new int [2];
// write code here
//由于求得数字有两个,进行异或之后,还需要把两个数字区分开
int xorResult = 0 ;
for(int i = 0;i<array.length;i++){
xorResult = xorResult ^ array[i];
}
//找到第一次出现1位数
int k = 0;
while((xorResult & 1) == 0){
k++;
xorResult = xorResult >> 1;
}
for(int i = 0;i<array.length;i++){
if(((array[i] >> k) &1) == 1){
res[0] = res[0] ^ array[i];
}else{
res[1] = res[1] ^ array[i];
}
}
//比较两个数字大小,简单排序
if(res[0]>res[1]){
int temp = res[0];
res[0] = res[1];
res[1] = temp;
}
return res;
}
}
#面试必刷题TOP101#
