61.找出数组中两个只出现一次的数字(数组)
题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。
请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
分析:这是一道很新颖的关于位运算的面试题。
package com.interview.algorithm;
/*
* 一个数和自己xor,返回0。1^1=0 0^0=0 1^0 = 1 0^1 = 1
*/
public class OnceChar {
public int AllXor(char[] c){
int all = 0;
for(int i = 0; i < c.length; i++){
all = all^c[i];
}
return all;
}
//返回倒数几位
public int getFirstOne(int num){
int pos = 1;
while((num & 0x01) == 0){
num = num >> 1;
pos++;
}
return pos;
}
public char[] getOnceChar(char[] c){
int xor = this.AllXor(c);
int firstOne = this.getFirstOne(xor);
char[] res = new char[2];
int num1 = 0; int num2 = 0;
for(int i = 0; i < c.length; i++){
if(this.isOne(firstOne, c[i]) == 0){
num1 = num1 ^ c[i];
}else{
num2 = num2 ^ c[i];
}
}
res[0] = (char)num1;
res[1] = (char)num2;
return res;
}
//如果最后一位是1,不用移位
public int isOne(int pos, char c){
int i = c >> (pos - 1);
int isOne = i & 0x01;
return isOne;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "AABBCDDEFF";
OnceChar once = new OnceChar();
char[] res = once.getOnceChar(str.toCharArray());
System.out.println(res[0]);
System.out.println(res[1]);
}
}