给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
哈希表性能优秀,但我不知道为什么put后再检查答案变得很奇怪
比如测试用例 twoSum([3,3],6)
返回的居然是[1,1]
恳求指点迷津

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
哈希表性能优秀,但我不知道为什么put后再检查答案变得很奇怪
比如测试用例 twoSum([3,3],6)
返回的居然是[1,1]
恳求指点迷津
本文标题:Leetcode1. 两数之和
本文链接:https://www.haomeiwen.com/subject/pujpmftx.html
网友评论
public int[] twoSum(int[] array,int targetValue){
HashMap<Integer,Integer> orignalMap = new HashMap<>();
int[] restIndex = new int[2];
//step1.initial the hashmap by using array value,index as key and value
for(int i = 0; i < array.length;i++){
orignalMap.put(array[i],i);
}
//step2.find the two value by hashmap data
for(int j = 0;j< array.length;j++){
int gap = targetValue - array[j];
Integer value = null;
if((value = orignalMap.get(Integer.valueOf(gap))) != null){
restIndex[0] = j + 1;
restIndex[1] = value + 1;
break;
}
}
return restIndex;
}