題目
給定一個整數數組,返回兩個數的索引,這兩個數相加等於特定的目標。
你可以假定每次輸入只有一個解決方案,並且你不會使用相同的元素兩次。
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
難度:Easy
思路
題目要求在數組中尋找兩個數A和B,相加等於一個特定的數traget,返回A和B的索引,**我們可以用給定的數traget減去A,看B是否存在於數組中即可**。
代碼實現
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { for (let i = 0; i < nums.length; i++) { let result = target - nums[i] let key = nums.indexOf(result) if (key !== -1 && i !== key) { return [i, key] } } }