Two Sum

Problem:

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

Leetcode
Lintcode

Solution

We can use a hash map to record the occurrence and index of integers.

When we go through the list, the key (target - current integer) exits in the hash map, then we can return current index and index corresponding to (target - current integer).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*************************************************************************
> File Name: TwoSum.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Wed 11 Nov 17:49:20 2015
************************************************************************/


public class TwoSum{
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();

for (int i = 0; i < nums.length ; i++){
if (map.containsKey(nums[i])) continue;

if (map.containsKey(target - nums[i])){
int[] result = {map.get(target - nums[i]) + 1, i + 1};
return result;
}

map.put(nums[i],i);
}

return null;
}
}

Related Problem:
3Sum
4Sum
3Sum Closest