问题描述
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.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
问题分析
the start of leetcode!
通过hashmap来加快读取速度,键放target-每个数的结果,值放这个数的下标i。每次放入的时候考虑键是否存在,存在说明当前数的index和hashmap里的下标i即为所求。不过最后两个值都需要加1才是正确答案,详情见代码。
代码实现
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < numbers.length; i++) {
if (hashMap.containsKey(numbers[i])) {
result[0] = hashMap.get(numbers[i]) + 1;
result[1] = i + 1;
break;
} else hashMap.put(target - numbers[i], i);
}
return result;
}
网友评论