Si usted tiene cantidades que no pueden ser XORed razonable (Grandes números enteros o números representan como cadenas, por ejemplo), un enfoque alternativo, que también es O (n), (pero O (n) espacio en lugar de O (1) espacio) sería simplemente usar una tabla hash. El algoritmo se parece a:
Create a hash table of the same size as the list
For every item in the list:
If item is a key in hash table
then remove item from hash table
else add item to hash table with nominal value
At the end, there should be exactly one item in the hash table
lo haría código, C o C++, pero ninguno de ellos ha tablas hash construido en (No me pregunte por qué C++ no tiene una tabla hash en el STL,. pero tiene un mapa hash basado en un árbol rojo-negro, porque no tengo idea de lo que estaban pensando.) Y, desafortunadamente, no tengo un compilador C# a mano para probar los errores de sintaxis, así que te doy Código Java Es bastante similar, sin embargo.
import java.util.Hashtable;
import java.util.List;
class FindUnique {
public static <T> T findUnique(List<T> list) {
Hashtable<T,Character> ht = new Hashtable<T,Character>(list.size());
for (T item : list) {
if (ht.containsKey(item)) {
ht.remove(item);
} else {
ht.put(item,'x');
}
}
return ht.keys().nextElement();
}
}
@Prasoon: buena solución, Prasoon :-) – Nawaz
@Nawaz: :) [.....] –
@Prasoon: por cierto, ¿es necesaria la plantilla de función? 'sizeof (a)/sizeof (a [0])' no es suficiente? – Nawaz