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<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;
}
}