[算法]给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。

给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。函数twoSum返回这两个相加起来等于目标值的数字的索引,且index1必须小于index2。请记住你返回的答案(包括index1index2)都不是从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]);

}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值