Given an array of integers, every element appears three times except for one. Find that single one.
e.g. 数组{1,2,3,1,1,3,2,2,3,54,66,54,54} 中 特殊数字是66,他只出现1次,其他数字出现3次。
/**
* Given an array of integers, every element appears three times except for one. Find that single one.
*/
public static void findSpecialNum() {
//构造一个符合条件的数组
//产生diffNum个不同的数字
int diffNum = 4;
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
int x = (int) (Math.random() * 100);
if (!list.contains(x)) {
list.add(x);
}
if (list.size() == diffNum) {
break;
}
}
ArrayList<Integer> list0 = new ArrayList<>();
int index = (int) (Math.random() * diffNum);
for (int i = 0; i < diffNum; i++) {
list0.add(list.get(i));
if (i != index) {
list0.add(list.get(i));
list0.add(list.get(i));
}
}
Collections.shuffle(list0);
Integer[] array = list0.toArray(new Integer[list0.size()]);
for (int i = 0; i < array.length; i++) {
//打印出构造的无序数组
System.out.println("findSpecialNum--" + array[i]);
}
for (int i = 0; i < array.length; i++) {
int count = 0;
int x = array[i];
for (int j = 0; j < array.length; j++) {
if(array[j]==x){
count++;
}
}
if(count >= 3){
continue;
}else{
System.out.println("findSpecialNum--is=" + array[i]);
}
}
}
上面构造出来的数组是随机的,每次运行后结果不同,但均能计算出特殊数字。
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--96
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--78
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--78
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--96
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--83
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--29
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--96
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--83
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--83
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--78
12-15 18:46:25.231 15036-15036/? I/System.out: findSpecialNum--is=29