在一个博客上看到一个这样的算法题:一个数组中有三个数字a、b、c只出现一次,其他数字都出现了两次,请找出三个只出现一次的数字。(原题地址:微软、Googel等面试题)
在不考虑时间和空间复杂度的条件下,使用java语言实现了该算法。首先使用一个数组des[]作为保存所要寻找的三个数字, 同时使用一个数组temp[] 作为保存出现两次的数字的下标,对于只出现一次的使用 -1保存。
如图: 上图为原始数据,下图保存下标。
下面是实现代码:
public class Demo {
public static void main(String[] args) {
// 测试数组
int[] array = {5,1,10,2,7,2,5,10,7,11,20};
int[] b = new int[3];
// 打印测试数组
for(int i=0; i<array.length; i++) {
System.out.print( array[i] + " ");
}
System.out.println("");
b=findNumber(array);
// 打印数组
for(int i=0; i<b.length; i++) {
System.out.print( b[i] + " ");
}
System.out.println("");
}
public static int[] findNumber(int[] array) {
int flag =0;
int[] des = new int[3];// 保存只出现一次的数字
int[] temp = new int[array.length];// 保存数组下标
for( int i=0; i<array.length; i++ ) {
for( int j=0; j<array.length; j++) {
if( array[i] != array[j] && i!=j) {
continue;
}
if( array[i] == array[j] && i!=j) {
temp[j] =j; // 下标赋值
break;
}else{
temp[i] = -1; // 只出现一次标识为-1
}
}
}
for( int k=0; k<temp.length; k++) {
if( temp[k] == -1) { // 查找标识为-1 下标
des[flag] = array[k];flag++;
}
}
return des;
}
}
End: 如需看原题的实现,请看上面连接地址。