题目:
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
上来我先用暴力方法来破解,答案是对的,但是超时。然后我又改用将原数组复制,然后排列,利用一次遍历来找到结果,再进行定位,可能有地方没有想到,最后也是超时。第二天我试着用HashMap这才成功解决掉。代码如下:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
Map map = new HashMap();
int[] result = new int[2];
for (int i = 0 ; i < numbers.length; i++)
{
if(map.get(target-numbers[i]) != null && (int)map.get(target-numbers[i]) != i+1)
{
result[1] = i+1;
result[0] = (int)map.get(target-numbers[i]);
break;
}
map.put(numbers[i],i+1);
}
return result;
}
}
这个可以AC,但是我发现如果测试用例为{0,2,3,0,1,0},这样的话,会出现结果是1、6,这是错的,然后又进行了改进:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
Map map = new HashMap();
for(int i = 0; i < numbers.length; i++)
{
map.put(numbers[i], i+1);
}
int[] result = new int[2];
for (int i = 0 ; i < numbers.length; i++)
{
if(map.get(target-numbers[i]) != null && (int)map.get(target-numbers[i]) != i+1)
{
result[0] = i+1;
result[1] = (int)map.get(target-numbers[i]);
break;
}
}
return result;
}
}