两数之和
解题思路
使用一个字典来对target - nums[i]进行存储,因为题目中要求对下标进行返回,那么我们就将键设置为target - nums[i],对应的值为nums[i]所对应的下标
代码
最开始我的代码是这样
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp = dict()
for j, i in enumerate(nums):
if temp[target - i] is not None:
return [j, temp[target - i]]
temp[nums[j]] = j
但是报错
KeyError: 3
原因是temp[target - i]
这个字段是不存在的,而我的目的是想判断temp[target - i]
是否存在对应的值,我在网上查询到了一种方法就是用字典的get
方法来代替
修改后的代码如下
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
temp = dict()
for j, i in enumerate(nums):
if temp.get(target - i) is not None:
return [j, temp[target - i]]
temp[nums[j]] = j
运行结果如下