JAVA实现在一个数组中找出两个数,其和为目标值
1、算法实现:
public class TwoSum {
/**
* 在指定数组中找出和为 target 的两个值
*
* @param nums 输入数组
* @param target 目标和
* @return 下标及值
*/
public Map<Integer, Integer> twoSum(int[] nums, int target){
Map<Integer, Integer> result = new HashMap<>(16);
Map<Integer, Integer> temp = new HashMap<>(16);
for(int i=0;i<nums.length;i++){
if(temp.get(target - nums[i]) != null){
result.put(temp.get(target - nums[i]), target - nums[i]);
result.put(i, nums[i]);
break;
}else {
temp.put(nums[i], i);
}
}
return result;
}
}
2、算法测试:
public class TestTwoSum {
@Test
public void twoSum(){
int[] nums = {10,34,1,2,4,6,7};
TwoSum twoSum = new TwoSum();
Map<Integer, Integer> integerIntegerMap = twoSum.twoSum(nums, 13);
integerIntegerMap.forEach((key,value) ->{
System.out.println("key:" + key + ";" + "value:" + value);
});
}
}
3、测试结果:
key:5;value:6
key:6;value:7
Process finished with exit code 0
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:33
阅读量:116
阅读量:114
阅读量:54
阅读量:47