对于这个问题,O(N ^ 2)不被认为“足够快”吗?
这里我列出了10,000,000个具有随机对值的元素.在一个随机点,我把“孤独的整数”5,O(N ^ 2)快速解决它而不需要排序.算法停在它找到的第一个“孤独整数”上.
public static void main(String[] args) {
Random r = new Random();
List ints = new ArrayList<>();
for (int i = 0; i < 10000000; i += 2) {
int randomNumber = r.nextInt(100) + 10;
ints.add(randomNumber);
ints.add(randomNumber);
}
ints.add(5); // Lonely Integer
int tempIndex = r.nextInt(ints.size());
int tempValue = ints.get(tempIndex);
// Swap duplicate integer with lonely integer
ints.set(tempIndex, ints.get(ints.size() - 1));
ints.set(ints.size() - 1, tempValue);
for (int i = 0; i < ints.size(); i++) {
boolean singleInteger = true;
for (int j = 0; j < ints.size(); j++) {
if (j == i) {
continue;
}
if (ints.get(j) == ints.get(i)) {
singleInteger = false;
break;
}
}
if (singleInteger) {
System.out.println("Single instance: " + ints.get(i));
break;
}
}
}
结果:
Single instance: 5 (about 10 – 20 seconds);
更新
你的方法大约3秒钟.
地图解决方案
public static void main(String[] args) {
Random r = new Random();
List ints = new ArrayList<>();
for (int i = 0; i < 10000000; i += 2) {
int randomNumber = r.nextInt(100) + 10;
ints.add(randomNumber);
ints.add(randomNumber);
}
ints.add(5); // Lonely Integer
int tempIndex = r.nextInt(ints.size());
int tempValue = ints.get(tempIndex);
// Swap duplicate integer with lonely integer
ints.set(tempIndex, ints.get(ints.size() - 1));
ints.set(ints.size() - 1, tempValue);
Map counts = new HashMap<>();
for (int i : ints) {
if (counts.containsKey(i)) {
counts.put(i, counts.get(i) + 1);
} else {
counts.put(i, 1);
}
}
for (Integer key : counts.keySet()) {
if (counts.get(key) == 1) {
System.out.println("Single Instance: " + key);
}
}
}
结果:
Single Instance: 5 (about 1 – 3 seconds)