Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
import java.util.Hashtable;
/**
*
* |Given numbers = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
* @author echo
*
*/
public class Solution {
public int[] twoSum(int[] numbers,int target){
int[] result = new int[2];//开一个盛放结果的数组
Hashtable<Integer, Integer> numsHashtable = new Hashtable<Integer,Integer>();
for (int i = 0; i < numbers.length; i++) {
//如果在hashtable中没有对应的值,则将对应值放入其中
//放入规则:key-数组的值,value-数组的下标
Integer n = numsHashtable.get(numbers[i]);
if (n == null) {
numsHashtable.put(numbers[i], i);
}
//判断上一个数是否等于目标值减去当前值
n = numsHashtable.get(target-numbers[i]);
//如果上一个数存在,且下标没越界,则当前数下标与上一个数下标为最后结果
if (n!=null && n < i) {
result [0] = n;//上一个值的下标
result [1] = i;//当前值的下标
return result ;
}
}
return result ;
}
}