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
public int[] twoSum1(int[] numbers, int target) {
int[] result = new int[2];
for (int i = 0; i < numbers.length; i++) {
for (int j = i+1; j < numbers.length; j++) {
if (target == numbers[i]+numbers[j]) {
result[0] = i+1;
result[1] = j+1;
return result;
}
}
}
return result;
}
很显然,超时。分析上述代码,外层循环是必须的,但是内层循环主要为了找到匹配的值,如果能在O(1)的复杂度找到target-numbers[i]的值即可,于是肯定要使用HashTable;自己的代码:
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for (int i = 0; i < numbers.length; i++) {
map.put(numbers[i], i+1);
}
for (Integer value : map.keySet()) {
Integer index2 = map.get(target-value);
if (index2 != null) {
int index1 = map.get(value);
if (index1 < index2) {
result[0] = index1;
result[1] = index2;
} else if (index1 == index2) {
for (int i = 0; i < numbers.length && index1 != i+1; i++) {
if (numbers[i] == value) {
result[0] = i+1;
result[1] = index1;
break;
}
}
} else if (index1 > index2) {
result[0] = index2;
result[1] = index1;
}
return result;
}
}
return result;
}
代码比较好懂,但是也比较臃肿。第一个for循环,往hash表里放值。第二个循环就有很多问题,因为如果出现{0,2,3,0} target=0的测试用例时,会发现hash表里只是存储了一个0。另外一个又查找了一遍,很是蛋疼。下面又做了修改:
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
for (int i = 0; i < numbers.length; i++) {
map.put(numbers[i], i+1);
}
for (int i = 0; i < numbers.length; i++) {
if (map.get(target-numbers[i]) != null && map.get(target-numbers[i]) != i+1) {
result[0] = i+1;
result[1] = map.get(target-numbers[i]);
return result;
}
}
return result;
}
这种代码很巧妙,尤其是第二个循环,可想而知,从前往后遍历,因为是成对出现的,而如果出现上述情况,显然为<3,3>,而遍历是从头开始的,所以也很容易知道哪个index比较小。在优化一下,把两个for循环合并成一个:
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < numbers.length; i++){
Integer diff = (Integer)(target - numbers[i]);
if(map.containsKey(diff)){
int toReturn[] = {map.get(diff)+1, i+1};
return toReturn;
}
map.put(numbers[i], i);
}
return null;
}
多思考,多优化,多总结!!!