题目链接
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
python实现:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for index, num in enumerate(nums):
if target - num in dict:
return [dict[target - num], index]
dict[num] = index
s = Solution()
res = s.twoSum([3, 4, 3], 6)
print(res)
JavaScript实现:
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for(i in nums){
let temp = nums[i]
let leave = target - temp
nums[i] = null
let index = nums.indexOf(leave)
// console.log(nums)
// console.log(i+''+index)
// console.log(i != index)
// console.log(leave)
// console.log(typeof(leave))
// console.log(nums)
// console.log(leave in nums)
if (i != index && index !== -1){
return [parseInt(i),index]
}
}
};
let res = twoSum([2, 7, 11, 15], 9)
console.log(res)