1. Two Sum

来源:互联网 发布:js div 编辑:程序博客网 时间:2024/05/12 12:07

问题:

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


分析:

方法1 - 最直接的方法可以用穷举:用两个for循环来测试得到的组合是否符合要求。会超时!(O(n^2), O(1))

方法2 - 逐个计算每个数组元素要的到target需要加上的那个数,再扫描数组中是否出现这个数。并没有任何改进。估计也会超时。(O(n^2), O(1))

方法3 - 思路来自于方法2,对于检查存在性的问题HashMap、HashSet是最能优化时间复杂度的。用HashMap改进方法2。(O(n), O(n))


代码:

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


0 0