####Question:
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.
####Example:
Input: numbers[]={2,7,11,15},
target = 9
Output: index1 =1, index2 = 2
其实,问题还是挺简单。意思就是说,给你一个数组 a 和一个数 c ,找出数组里面两个元素 a[i] 和 a[j] 加起来的和等于c。你需要返回这两个元素的下标,并且 i < j。
####思路:
- 加法:让数组里面两个数加起来去跟target比较是,时间复杂度是O(n^2),即 是两个for循环遍历数组a。
- 减法:用target依次减去数组的元素a[i],把差遍历后面的数组a[i+1]…a[n],判断数组里是否有元素等于这个差。其实也是两个for循环,时间复杂度也是O(n^2)。
####下面,我使用减法来做。
package TwoSum;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static void main(String[] args) {
TwoSum t = new TwoSum();
int [] numbers= {2,7,11,15};
int target = 13;
int [] res = t.twoSum(numbers, target);
for(int i = 0; i < res.length; i++)
System.out.print(i==res.length-1? res[i]:res[i]+",");
}
//返回两个下标
public int[] twoSum(int[] numbers, int target){
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < numbers.length; i++)
map.put(numbers[i], i);
for(int i = 0; i < numbers.length; i++){
int newTarget = target - numbers[i];
if(map.containsKey(newTarget)&&i < map.get(newTarget))
return new int[]{i + 1, map.get(newTarget) + 1 };
}
return null;
}
}