给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
方法一
使用for循环,直接找出是否存在target-num[i]
class Solution(object):
def twoSum(self, nums, target):
for i in range(len(nums)):
j = target -nums[i]
if j in nums :
k = nums.index(j)
if k!=i:
return [i,k]
方法二
使用字典,将值作为键,位置作为值查询
class Solution(object):
def twoSum(self, nums, target):
dict_a = {}
for i in range(len(nums)):
if nums[i] in dict_a:
return [dict_a[nums[i]], i]
else:
dict_a[target - nums[i]] = i