I have a 2D Array and I would like to find an easier way to manipulate my code so that it will find if there is a duplicate in the column and easier way then what I have below:
for (int i=0; i < array.length; i++) {
for (int j=0; j < array.length; j++) {
for (int k=1; k < array.length; k++){
if (array[j+k][i] == array[j][i]) {
if (array[j][i] != 0) {
return true;
}
}
}
}
}
return false;
EDIT: KINDLY POINTED OUT THE ABOVE ^^ WON’T WORK EITHER AS IT WILL THROW AN OUT OF BOUNDS EXCEPTION
This way has too many loops and I am sure there must be an easier way to find duplicates rather than going through this massive looping process.
This is for a square 2D array, ie. an array with rows = columns.
If so, how can this new way work – and how can I manipulate it to work to find duplicate values in the rows as well.
Thanks for the help.
you can use
HashSetto store all already encountered elements. should be something like this:this solution is O(length^2) = O(n) where n is the matrix total size. I think it is ideal in terms of big O, because you need to check all elements.