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減去每個數(shù)得到每個數(shù)需要的數(shù)字邓萨,然后把它存在hashmap的key中商虐,value存當(dāng)前數(shù)字的index须教。
所以每次我們只需用containsKey檢測當(dāng)前數(shù)字是否在key中和另一個數(shù)配對,如果配對仰冠,我們拿出index和當(dāng)前數(shù)字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<Integer, Integer> 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;
}
}