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].
思路:使用HashTable保存nums,Key为数值,value为索引,用于快速查找下标。遍历一次nums数组,每次判断target-num[i]是否在HashTable中,有则找到了,通过HashTable取得下标值,返回。
import java.util.Hashtable;
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
Hashtable<Integer, Integer> numbers = new Hashtable<>();
for (int i = 0; i < nums.length; i++) {
numbers.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int findNum = target - nums[i];
if (numbers.containsKey(findNum) && numbers.get(findNum) != i) {
res[0] = i;
res[1] = numbers.get(findNum);
break;
}
}
return res;
}
}