给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
解题思路:首先提取2个关键信息,一个是数组nums,一个是目标值target(即数组某2个元素之和),本题思路主要是:另一个元素 = 目标值 - 当前循环数组元素,很明显另一个元素也是数组中的元素。所以这里用了findIndex去查询索引(索引唯一且索引不重复)。这里要注意,题需要返回索引数组,所以需要在外部定义变量去记录索引,并且匹配到时停止循环。
// 方法1
const twoSum = function (nums,target){
let i1,i2;
array.some((item,index) => {
const other = target - item;
const otherIndex = nums.findIndex((_item,_index) => {
return index!==_index&&other === _item;
})
if(otherIndex !== -1){
i1 = index;
i2 = otherIndex;
return true;
}
})
return [i1,i2];
}
// 方法2
const twoSum = function (nums,target){
const map = new Map();
for(let i = 0; i < nums.length; i++){
if(map.has(target - nums[i])){
return [map.get(target - nums[i]),i]
}
map.set(nums[i],i)
}
}