Se si dispone di quantitativi che non possono essere ragionevolmente XORed (Grandi numeri interi o numeri rappresentati come stringhe, per esempio), un approccio alternativo che è anche O (n), (ma O (n) spazio piuttosto che O (1) spazio) sarebbe semplicemente utilizzare una tabella hash. L'algoritmo si presenta come:
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
che avrei fatto il codice, C o C++, ma nessuno dei due ha tabelle hash costruito nel (non chiedetemi perché C++ non ha una tabella hash nel STL,. ma ha una mappa hash basata su un albero rosso-nero, perché non ho idea di cosa stessero pensando.) E, sfortunatamente, non ho a disposizione un compilatore C# per testare gli errori di sintassi, quindi ti sto dando Codice Java È piuttosto simile, però.
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();
}
}
fonte
2011-01-23 08:56:32
@Prasoon: buona soluzione, Prasoon :-) – Nawaz
@Nawaz: :) [.....] –
@Prasoon: a proposito, è necessario il modello di funzione? 'sizeof (a)/sizeof (a [0])' non è abbastanza? – Nawaz