2Sum 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.
** Notice
You may assume that each input would have exactly one solution

用hashmap来做,我们用target减去每个数得到每个数需要的数字,然后把它存在hashmap的key中,value存当前数字的index。
所以每次我们只需用containsKey检测当前数字是否在key中和另一个数配对,如果配对,我们拿出index和当前数字index一起返回。

public class Solution {
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1 + 1, index2 + 1] (index1 < index2)
     */
    public int[] twoSum(int[] numbers, int target) {
        // write your code here
        
        HashMap map = new HashMap<>();
        
        for(int i = 0; i < numbers.length; i++) {
            if (map.containsKey(numbers[i])) {
                
                int[] result = {map.get(numbers[i]) + 1, i + 1};
                return result;
            }
            
            map.put(target - numbers[i], i);
        }
        
        int[] result = {};
        return result;
        
        
    }
    
    
    
}

你可能感兴趣的:(2Sum problem)