Accepted simple and clean Java code


  • 5
    M
    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;
    }

  • 0
    Y

    It's really a pretty solution !!!


  • 0
    X

    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?


  • 0
    M

    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.


  • 0
    X

    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.


  • 0
    A

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


  • 0
    M

    Yes, it is guaranteed. Thank you.


  • 0
    M
    This post is deleted!

Log in to reply
 

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