public class Solution {
public int[] twoSum(int[] numbers, int target) {
int a, b;
Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0; i<numbers.length; i++)
{
a=numbers[i];
b=target-a;
if(hm.containsKey(b)){
return new int[]{hm.get(b)+1,i+1};
}
hm.put(a, i);
}
return null;
}
}
--------------------------------------------
HINT:
1. HashMap的使用,因为这里需要通过Hashmap存储第一个index;通过减数找到对应的Index.
2. map拥有的方法:containsKey, put....
=========================
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 class Solution {
public int[] twoSum(int[] numbers, int target) {
Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i=0; i<numbers.length; i++){
hm.put(numbers[i],i);
}
int gap;
for(int i=0; i<numbers.length; i++){
gap = target - numbers[i];
if(hm.containsKey(gap) && hm.get(gap)!=i)
return new int[]{i+1,hm.get(gap)+1};
}
return null;
}
}