Share my concise Java solution


  • 1
    Y
        public int[] twoSum(int[] numbers, int target) {
        HashMap<Integer,Integer> map = new HashMap<Integer, Integer>(); 
        for(int i = 0; i < numbers.length; i++)      map.put( numbers[i], i+1);
        for(int i = 0; i < numbers.length; i++){
            int value = target - numbers[i];
            if(map.containsKey(value) && map.get(value) != i+1){
                int index = map.get(value) ;
                if(i+1 < index)      return new int[]{i+1, index};
                return new int[]{index, i+1};
            }     
        }
        return new int[0];
    }
    

    }

    Feel free to leave comment below as this probably could improve more. The only problem I am not sure with this is that, if the original input is something like [3,3,5] 6, then putting everything into map would result in a map of only two elements with key one 3 and one 5(duplicate 3 removed). Though my solution is accepted. Let me know how you think!


  • 0
    B

    What I did to eliminate the duplication (as far as a duplication is the target sum) was simply check to see if the target - current is in the table as a key, if not then you just add the current to the map.


  • 0
    Y

    typed the question wrong. Excuse me, I actually meant duplication of two numbers in the array but they sum up to target. but thanks to your suggestion, whenever there's duplication, just check if multiply it by 2 yields to target and return if true.


  • 2
    F

    Your solution is absolute correct. because when duplicate happened, your index of the duplicate in the map is the latest one

    Then when you in the second loop, even if the two number is duplicate, but you are right now at the position of first one, the map will return the second one. then it goes correct.

    for example {3,6,6,7,3}, 6: after the map initialization, key,3 -> value,5. then you start check from first, when checking the '3', the index is '1', but the map will return the value 5. then the answer is (1,5). correct.

    Hope it helps.


  • 0
    L

    thank you so much, you solve my confusion!


  • 0
    1
            if(i+1 < index)      return new int[]{i+1, index};
            return new int[]{index, i+1};
    

    i do not understand this part? couldn't we just simplify it to return new int[]{i+1, index};??


  • 0
    C

    I don't think so.For example{3,2,3,1,3,7},6.Your answer will be (1,5),but the correct should be (1,3).


  • 0
    D

    @changxinhua said in Share my concise Java solution:

    3
    There is a line in question:
    ! You may assume that each input would have exactly one solution.


Log in to reply
 

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