问题连接:https://oj.leetcode.com/problems/two-sum/
问题描述:
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.
API接口: public int[] twoSum(int[] numbers, int target)
这题已经是很老很经典的题了,在我三年前开始找工作的时候这题目就很流行了。
主要解题思路有二,一是用哈希表存遍历的值,一次遍历循环即可。key放的是target - number[i], value放的是index。
循环扫的时候对比是否存在当前number[i]的键,也就是找0 <= j < i的范围里,是否存在target - number[j] = number[i]. 找得到的话即可范围答案,没找到继续放入(target - number[i], i )的键值对,直到找到为止。时间O(n), 空间O(n)
代码如下:
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> cached = new HashMap<Integer, Integer>();
int[] res = new int[2];
for(int i = 0; i < numbers.length; i++){
if(cached.containsKey(numbers[i])){
res[0] = cached.get(numbers[i]) + 1;
res[1] = i + 1;
}else
cached.put(target - numbers[i], i);
}
return res;
}
第二种解题思路基于排序,但因为本题要求返回的是index,所以返回起来比较麻烦。会在后面的另一题放出相对的代码。