给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。函数twoSum返回这两个相加起来等于目标值的数字的索引,且index1必须小于index2。请记住你返回的答案(包括index1和index2)都不是从0开始的。你可以假定每个输入都有且仅有一个解决方案。输入: numbers={2, 7, 11, 15}, target=9输出: index1=1, index2=2
import java.util.HashMap;
public class Solution
{
public static int[] towSum(int[] nums,int target)
{
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] result = new int[2];
for(int i = 0; i < nums.length; i++)
{
map.put(nums[i], i);
}
for(int i = 0; i < nums.length; i++)
{
int searched = target - nums[i];
if(map.containsKey(searched) && map.get(searched) != i)
{
int index = map.get(searched);
if(index < i)
{
result[0] = map.get(searched) + 1;
result[1] = i + 1;
}
else
{
result[0] = i + 1;
result[1] = map.get(searched) + 1;
}
}
}
return result;
}
public static void main(String[] args)
{
int[] nums = {2,7,11,15};
int target = 9;
int[] result = new int[2];
result = Solution.towSum(nums,target);
System.out.println(result[0]+" "+result[1]);
}
}