- 求一个数组中两个数的和为某个指定值
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
/**
*
* @param nums
* @param target
* @return Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
*/
public static int[] twoSum(int[] nums,int target){
final HashMap<Integer,Integer> myMap=new HashMap<>();
for (int i=0;i<nums.length;++i){
myMap.put(nums[i],i);
}
for (int i=0;i<nums.length;++i){
final Integer v=myMap.get(target-nums[i]);
if (null!=v && v>i){
return new int[]{i+1,v+1};
}
}
return new int[]{-1,-1};
}