leetcode-two sum

来源:互联网 发布:58淘宝模特兼职的骗局 编辑:程序博客网 时间:2024/04/30 11:27

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

public class Solution {    public int[] twoSum(int[] numbers, int target) {        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();        int len =numbers.length;        if(len<=1)return null;        for(int i=0;i<len;i++){            int dif=target-numbers[i];            if(map.containsKey(dif)){               int[] result={map.get(dif)+1,i+1};                return result;            }            map.put(numbers[i],i);        }        return null;    }}
1 the same key value can only have once.

2 still the same idea with three or four keys. make one set, and try the other one. 

3 The most wonderful character about hash table is that it can remember past keys and the value associated with it. And can efficiently search!

0 0
原创粉丝点击