2015-01-05 15:29:20

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

时间复杂度O（n）

1.     public static int[] twoSum(int[] numbers, int target) {
2.         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
3.         int ret[] = {-1, -1};
4.         for (int i = 0; i < numbers.length; i++) {
5.             map.put(numbers[i], i);
6.         }
7.         for (int i = 0; i < numbers.length; i++) {
8.             if (map.containsKey(target - numbers[i])) {
9.                 if (map.get(target - numbers[i]) != i) {
10.                     ret = i + 1;
11.                     ret = map.get(target - numbers[i]) + 1;
12.                     break;
13.                 }
14.             }
15.         }
16.         return ret;
17.     }