So I am trying to write a function that checks if there is duplicates inside an array. Once the function detects a duplicate I want it exit break out of the loop and return type. However in my case it keeps on looping as if the break does not exist. Can please someone explain for me why this happening?
public static boolean singleNumber(int[] nums) {
boolean type = false;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j <= nums.length - 1; j++) {
if (nums[i] == nums[j]) {
type = true;
break;
}
}
}
return type;
}
The break
will only get out of the inner loop, not both loops. One option is to just return true
instead of break. And return false
at the end of the method if there is no early return. No need for the type
variable in this case.