1. 題目
https://leetcode-cn.com/problems/two-sum/
給定一個(gè)整數(shù)數(shù)組 nums 和一個(gè)目標(biāo)值 target笛臣,請(qǐng)你在該數(shù)組中找出和為目標(biāo)值的那 兩個(gè) 整數(shù),并返回他們的數(shù)組下標(biāo)牵素。
你可以假設(shè)每種輸入只會(huì)對(duì)應(yīng)一個(gè)答案。但是,你不能重復(fù)利用這個(gè)數(shù)組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2. 我的AC
推算一遍
i = 0, num = 2
dic[9-2] = 0, {7:0} # 7的match位在0處
i = 1, num = 7
return [0, 1]
----
i = 2, num = 11
dic[9-11] = 0, {-2:2}
i = 3, num = 15
dic[9-15] = 0, {-6:3}
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i, num in enumerate(nums):
if num in dic:
return [dic[num], i]
else:
dic[target - num] = i
3. 小結(jié)
- 看到精練的代碼不理解憾筏,可以按照程序一步步推演一遍,推完就懂了