两数之和数组
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你能够假设每种输入只会对应一个答案。可是,你不能重复利用这个数组中一样的元素。spa
给定 nums = [2, 7, 11, 15], target = 9code
由于 nums[0] + nums[1] = 2 + 7 = 9 因此返回 [0, 1]cdn
var twoSum = function(nums, target) {
const comp = {};
for(let i=0; i<nums.length; i++){
if(comp[nums[i] ]>=0){
return [ comp[nums[i] ] , i]
}
comp[target-nums[i]] = i
}
};
复制代码
关键在于:comp 这个对象对象
key: 存取 目标(target) - num[i] 的结果blog
value: 存取 能算出该结果的索引值索引
逻辑以下:leetcode
comp[2] 为 undefindget
9 - 2 = 7;it
也就是只须要找到下个数值为7的时候就是想要的。
comp[7] 在comp对象中有:
说明 以前计算过 7 这个数字有匹配的。
直接返回 以前的索引:comp[7], 当前索引