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
.
CodePudding user response:
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;
}
CodePudding user response:
You can also iterate over the array once if you use a HashSet. If the add() returns false then we know we have seen that number before.
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
HashSet<Integer> duplicateSet = new HashSet<>();
for (int i = 0; i < input.length; i ) {
if(!duplicateSet.add(Integer.valueOf(input[i])))
{
hasDuplicates = true;
break;
}
}
return hasDuplicates;
CodePudding user response:
You can take the benefit of Set data-structure as well:
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
Set<Integer> set = new HashSet<>(input.length);
for (int i : input) {
if (set.add(i)) {
hasDuplicates = false;
}
else {
hasDuplicates = true;
break;
}
}
Set add(E e) returns true if this set did not already contain the specified element.
In a short way:
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
Set<Integer> set = new HashSet<>(input.length);
for (int i : input) {
if (!set.add(i)) {
hasDuplicates = true;
break;
}
}
CodePudding user response:
Java 8 makes life easier. here you go
int[] input = {1, 2, 3, 4, 1};
boolean hasDuplicates = false;
if(Arrays.stream(input).distinct().count() != input.length)
hasDuplicates=true;
System.out.println(hasDuplicates);