2Sum

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

Analysis

  • 注意这里不能直接用2 pointers来解题。因为2 pointers解法要求sort array。但是本题需要返回数据本来的index。sort了以后就找不到原来的index了。所以需要用别的方法。
  • 如果nums里面有重复,code也成立
  • Keep a hashmap, key is nums[i], value is i+1
  • for i=0, len-1

    • if map does not has target - nums[i], add (nums[i],i)

    • if map has target - nums[i] return map.get(target - nums[i])+1, i+1

Code

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums==null || nums.length==0) {return new int[]{0,0};}
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i=0; i<nums.length; i++){
            if (map.containsKey(target-nums[i])){
                return new int[]{map.get(target-nums[i])+1, i+1};
            }
            else {
                map.put(nums[i],i);
            }
        }
        return new int[]{0,0};
    }
}

Reference

yuanbin: check for another method using 2 pointers