LeetCode #1 Two Sum (M)

[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

 

[Analysis]

对数组进行一次扫描,利用一个Hash Table结构记录已出现的数字以及索引,在扫描一个新数字时,只需要检查(target - current)的数值是否已在Hash Table里存在。由于题目提示可以假定每组输入只有唯一解,可以省略重复或顺序等检测逻辑,比较简单。注意返回值不是zero-based。


[Solution]

public class Solution {
    public static int[] twoSum(int[] numbers, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            int x = numbers[i];
            if (map.containsKey(target - x)) {
                return new int[] { map.get(target - x) + 1, i + 1 };
            }
            
            map.put(x, i);
        }
        
        return new int[2];
    }
}

 

posted on 2015-09-30 00:01  张惬意  阅读(92)  评论(0编辑  收藏  举报