Issue
I was asked to write a code, which indicates, whether an integer array has duplicate elements or not. This is what I have so far:
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
for (int i = 0; i < input.length; i++) {
for (int j = i + 1; j < input.length; j++) {
if (input[i] != input[j]) {
hasDuplicates = false;
} else if (input[i] == input[j]) {
hasDuplicates = true;
}
}
}
However, this code does not work as it was intended to be, because hasDuplicates
is always false
.
Solution
Once you have decided that the array hasDuplicates
, you may never change that; you can't make disappear the duplicate after. Also use break
the loop, at the moment hasDuplicates
becomes true
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
for (int i = 0; i < input.length; i++) {
for (int j = i + 1; j < input.length; j++) {
if (input[i] == input[j]) {
hasDuplicates = true;
break;
}
}
if (hasDuplicates)
break;
}
Even easier in a method, directly use return
static boolean hasDup(int[] input) {
for (int i = 0; i < input.length; i++)
for (int j = i + 1; j < input.length; j++)
if (input[i] == input[j])
return true;
return false;
}
Answered By - azro