标签:
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
给出一组整数,找到两个数A和B,使得A+B=目标数。输出这两个数的index,从小到大,并且注意不要从0开始计数,如下所示。你可以假设有且只有一个解。
1 public static int[] twoSum(int[] numbers, int target) { 2 int[] res = new int[2]; 3 HashMap<Integer,Integer> nums = new HashMap<Integer,Integer>(); 4 for(int i=0;i<numbers.length;i++){ 5 Integer a = nums.get(numbers[i]); 6 if(a == null){ 7 nums.put(numbers[i], i); 8 } 9 a = nums.get(target - numbers[i]); 10 if(a!=null&&a<i){ 11 //说明找到解了 12 res[0] = a+1; 13 res[1] = i+1; 14 break; 15 }else{ 16 res[0] = -1; 17 res[1] = -1; 18 } 19 } 20 return res; 21 22 }
标签:
原文地址:http://www.cnblogs.com/liyuhui21310122/p/4480612.html