Very short and simple Java code for Two Sum


  • 41
    O
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            
            HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
            for(int i = 0; i < numbers.length; i++){
    
                Integer diff = (Integer)(target - numbers[i]);
                if(hash.containsKey(diff)){
                    int toReturn[] = {hash.get(diff)+1, i+1};
                    return toReturn;
                }
    
                hash.put(numbers[i], i);
    
            }
            
            return null;
            
        }
    }
    

    So the simplest solution using a HashMap is to simply throw all the data in there to start with, then iterate through all of the numbers to see if (target-num) is in there, and if it is, return {lower index, higher index}.

    However, we can cut down on some runtime and code length by doing it in a single for loop.

    We know that the first number is strictly less than the second number (implying not equal), so if we are returning {value found in HashMap, current loop iteration} then we can be certain that we will never have to insert a value in the HashMap before we check if its difference is. Because of this fact, we can do the inserting and checking in the same loop with no issues. This saves a bit on runtime and memory because it means that you are not guaranteed to have to save all of the data in the HashTable at the start.


  • 2
    M
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            
            if(numbers.length>=2)
            {
                HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();
                for(int i=0; i<numbers.length; i++){
                    if(!h.isEmpty() && h.containsKey(target-numbers[i]))
                    {
                        int[] k = {h.get(target-numbers[i])+1,i+1};
                        return k;
                    }
                    
                    h.put(numbers[i],i);
                }
            }
            
            int[] k = {-1,-1};
            return k;
        }
    }

  • 0
    R

    Brilliant!!!


  • 0
    A

    Efficient solution.


  • 0
    R

    How about the elements are the last two in numbers ?


  • 2
    C

    Just quick question. When you use "hash.containsKey(diff)." When did you put "diff" variable in hashmap? if not, hashmap should empty.


  • 5
    N

    Why adding +1 in toReturn ? Since we have to give indices ? they should just be i instead of i+1 or the hash.get(secondnumber or diff) instead of hash.get(diff)+1


  • 0
    P

    @nikhil.kataria I believe so.
    Cuz index just starts from 0, no need to add 1.


  • 0
    W

    @PeiwenLiu I think maybe the question has been changed...and you can notice that the variable int[] nums was int[] numbers previously.


  • 0
    R

    @winechen9 You are right, the question has been changed. The result of this solution is no longer working, but it will be correct by just removing the "+1"


Log in to reply
 

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