Leetcode: Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

public int[] twoSum(int[] numbers, int target) {
        //use hashmap to store <val,index> pairs of all the numbers
        //in this algorithm, we assume all the numbers are different
        //and we need to add one to the index as the final output as requried by this question
        int[] output = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
        for(int i=0;i<numbers.length;i++){
            map.put(numbers[i],i);
        }
        for(int i=0;i<numbers.length;i++){
            int val = target-numbers[i];
            if(map.containsKey(val)){
                int index = map.get(val);
                if(index!=i){
                    if(i<index){
                        output[0] = i+1;
                        output[1] = index+1;
                    }else{
                        output[0] = index+1;
                        output[1] = i+1;
                    }
                    return output;
                }
            }
        }
        return output;
    }

The time complexity is O(N). Since we only need constant time for each HashMap search operation.

FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *