題目
給定一個整數(shù)數(shù)組 nums 和一個目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個答案灼擂。但是,你不能重復(fù)利用這個數(shù)組中同樣的元素觉至。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有剔应。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處语御。
解答
function twoSum(nums, target) {
const cached = {}
for(let i = 0, l = nums.length; i < l; i++) {
const remain = target - nums[i]
if (cached[remain] !== undefined) {
return [cached[remain], i]
}
cached[nums[i]] = i
}
return []
}