【发布时间】:2020-04-09 23:57:08
【问题描述】:
两个和 给定一个整数数组,返回两个数字的索引,使它们相加为特定目标。
您可以假设每个输入都只有一个解决方案,并且您不能两次使用相同的元素
例子:
给定 nums = [2, 7, 11, 15],目标 = 9,
因为 nums[0] + nums[1] = 2 + 7 = 9, 返回 [0, 1]。
解决办法:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h:
h[num] = i
else:
return [h[n], i]
这对我来说毫无意义,请有人解释一下它是如何工作的?
【问题讨论】:
-
注意输入是 nums = [2, 7, 11, 15], target = 9,
-
使用步进调试器跟踪代码执行可能有助于您理解。
标签: python