题解 | 两数之和
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
int[] res=new int[2];
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<numbers.length;i++){
int temp= target - numbers[i]; //暂存目标值减去当前值
if(!map.containsKey(temp)){
map.put(numbers[i],i); //不包含就放入hash
}
else{
return new int[]{map.get(temp)+1,i+1}; //否则就返回他在hash中存的位置和当前位置 加1是因为下标都是从0开始。
}
}
return res;
}
}
关键点在于要怎么确定将哪些值存入map中。如果目标值减去当前值已经存在了map中,就可以返回这个暂存值的位置,以及当前遍历的位置,如果没有,那就要将当前值和位置存入map。
