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