题目
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example:
Input: nums = [2,7,11,15], target = 9 Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
输入一个数组和一个target值,返回数组中和为target值的两个数的下标。
思路
- 创建一个map
- for循环遍历nums数组
- 用target减去nums[i],以计算哪个数能跟当前的数字相加得到target
- 检查map里有没有这个数,如果有则返回结果;如果没有则把num[i]当做key,i当作value放入map中。(为什么不能把i当作key?)
答:检查map里有无对应的数时,要调用map.has()函数,它检查的是map里有没有对应的key,如果i在前,就找不到实际的value
代码
var twoSum = function(nums, target) {
const map = new map(); //创建一个空map
for(let i=0;i<nums.length;i++){ //遍历数组
const temp = target - nums[i]; //计算与num[i]相对应的结果
if (map.has(temp)){ //检查当前map里有没有这个结果
return [map.get(temp),i]; //如果有,返回其下标
}else{
map.set(nums[i],i); //如果没有,则将当前num[i],i加入map
}
return []; //若没有符合要求的数,则返回空值
}
};
参考资料
https://www.bilibili.com/video/BV1wA411b7qZ?p=1