escribí este código en C++ como parte de una tarea uni donde necesito para asegurarse de que no hay duplicados dentro de una matriz:¿Una manera más elegante de buscar duplicados en una matriz C++?
// Check for duplicate numbers in user inputted data
int i; // Need to declare i here so that it can be accessed by the 'inner' loop that starts on line 21
for(i = 0;i < 6; i++) { // Check each other number in the array
for(int j = i; j < 6; j++) { // Check the rest of the numbers
if(j != i) { // Makes sure don't check number against itself
if(userNumbers[i] == userNumbers[j]) {
b = true;
}
}
if(b == true) { // If there is a duplicate, change that particular number
cout << "Please re-enter number " << i + 1 << ". Duplicate numbers are not allowed:" << endl;
cin >> userNumbers[i];
}
} // Comparison loop
b = false; // Reset the boolean after each number entered has been checked
} // Main check loop
Funciona perfectamente, pero me gustaría saber si hay una forma más elegante o eficiente de verificar.
Pero si la ordenación es O (n * log (n)) y luego tiene que hacer una comprobación O (n) de la matriz para encontrar los duplicados después de que no sea su complejidad, entonces O (n^2 * log (n))? – Goz
No, es O (n * log (n) + n) - clasifica ENTONCES busca, no ordena Y busca cada operación del tipo. – Puppy
Esto es ciertamente más rápido cuando 6 se acerca al infinito ;-) –