I'm writing a method that takes (1) an array of int
s and (2) an int
. The purpose of the method is to find the indices of the two numbers in the array that add up to the value passed in as the second parameter to the method (sum) and return those values in an int[]
. Exactly two numbers in the passed in array will add up to "sum", so as soon as they are identified the method should finish. I have come up with two solutions so far, but both seem ugly to me:
//this method is bad because it has multiple returns
private int[] findIndexes(int[] intAr, int sum) {
for (int i = 0; i < intAr.length; ++i) {
for (int k = i + 1; k < intAr.length; ++k) {
if(intAr[i] + intAr[k] == sum) {
return new int[] {i + 1, k + 1};
}
}
}
//should never reach here
return null;
}
//this method is bad because it uses "break" outside of a switch statement
private int[] findIndexes(int[] intAr, int sum) {
int[] indexAr = new int[2];
outer:
for (int i = 0; i < intAr.length; ++i) {
for (int k = i + 1; k < intAr.length; ++k) {
if(intAr[i] + intAr[k] == sum) {
indexAr[0] = i + 1;
indexAr[1] = k + 1;
break outer;
}
}
}
return indexAr;
}
Is there a better way to write this method that does not violate the coding standards mentioned above?
The coding standards I was looking at are located here.
i
andk
in the array, but returning an array populated withi + 1
andk + 1
values (not contents)? If your code does what it's stated to, you are assuming that 'x[n] == n + 1' - not something I would bet on in the wild (non-contiguous arrays, starting values not at 1, etc). I would also startk
ati
, noti + 1
, in case the only way to match the sum is to double the number (and no duplicates in the array). Other than that, I like the first solution. – Clockwork-Muse Aug 2 '11 at 20:13