1. 题目描述:
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].
2. 思路分析:
逐渐建立一个hash
表,然后在其中查找。A+B=C
,变换成A=C-B
,这是一个思想的转变。
3. Java代码:
源代码
:见我GiHub主页
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> itemToIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
if (itemToIndex.containsKey(temp)) {
return new int[] {itemToIndex.get(temp), i};
}
itemToIndex.put(nums[i], i);
}
return null;
}