public int[] twoSum(int[] numbers, int target) {
int len = numbers.length;
Map<Integer, Integer> valIndices = new HashMap<Integer, Integer>();
int index1 = 0;
int index2 = 0;
for (int i = 0; i < len; ++i) {
int val = numbers[i];
if (valIndices.containsKey(val)) {
index1 = valIndices.get(val);
index2 = i + 1;
break;
}
valIndices.put(target  val, i + 1);
}
// The first index must be less than the second one
int[] retIndices = new int[2];
if (index1 < index2) {
retIndices[0] = index1;
retIndices[1] = index2;
} else {
retIndices[0] = index2;
retIndices[1] = index1;
}
return retIndices;
}
Accepted simple and clean Java code


I don't quite understand what is your question. But, of course this code works for other cases. For example, for the case that numbers=[1, 2, 4, 3] and target=5, then the valIndices will have the following (key,value)={(4,1), (3,2)} respectively for the first and second step, then for the third step, when we are coming to 4 in the array, we find that it's in valIndices, so we get that index and return.