1.两数之和
(1)题目
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是数组中同一个元素不能使用两遍。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
(2)python代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
find_num=target-nums[i]
if find_num in nums[i+1:]:
return [i,nums.index(target-nums[i],i+1)]
else:
pass
结果:
(3)优化方案-python代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap={
}
for i,num in enumerate(nums):
hashmap[num] = i
for j,num_j in enumerate(nums):
k = hashmap.get(target - num_j)
if k is not None and j!=k:
return [j,k]
结果: