Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
使用HashMap存储数字,对每一个元素,查找target-nums[i]元素对应的下标,如果找到则返回结果。
java code:
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
Integer number = (Integer)map.get(nums[i]);
if (number == null) map.put(nums[i], i);
number = (Integer) map.get(target - nums[i]);
if (number != null && number != i) {
result[0] = number;
result[1] = i;
return result;
}
}
return result;
}
}