Two Sum

来源:互联网 发布:网络电视老是卡怎么办 编辑:程序博客网 时间:2024/04/28 07:35

Two Sum

 
AC Rate: 592/2417
My Submissions

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

这题选择了用HashMap来存储已经遍历过的元素,HashMap的对应关系是Value为元素下标,Key则是target与Value下标对应元素之差。

也就是说,每遍历一个元素,就看,map里有没有与它加和为target的key:

1.有。正在遍历的下标和map里存的下标,刚好就是所求。

2.没有。把这个元素所需的元素-本身的下标存进去。

HashMap的好处就是search的复杂度为O(1)    :D

public class Solution {    public int[] twoSum(int[] numbers, int target) {        // Start typing your Java solution below        // DO NOT write main() function        int res[] = new int[2];        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();        for(int i = 0; i<numbers.length; i++) {            if(!map.containsKey(numbers[i]))                map.put(target - numbers[i],i);            else {                int idx = map.get(numbers[i]);                if(idx < i) {                    res[0] = idx + 1;                    res[1] = i + 1;                    break;                }            }        }        return res;    }}