# Accepted simple and clean Java code

• ``````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;
}``````

• It's really a pretty solution !!!

• If the taget indexes are first and second it's all fine. But when the final indexes are (1, 3) or others? Can it still work?

• 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.

• I mean, for yor example, in second time, number=2, 1+2=3, so we need to find the next, in the third time, valIndices=3, and val=4...so it can not find the right number 4 for the original first number 1.

• There is no need to compare index1 and index2. In this algorithm, index 1 < index2 is guaranteed.

• Yes, it is guaranteed. Thank you.

• This post is deleted!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.