給定一個(gè)整數(shù)數(shù)組和一個(gè)目標(biāo)值争占,找出數(shù)組中和為目標(biāo)值的兩個(gè)數(shù)恃泪。
你可以假設(shè)每個(gè)輸入只對(duì)應(yīng)一種答案队腐,且同樣的元素不能被重復(fù)利用湿硝。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?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]
"""
d = dict()
for k, i in enumerate(nums):
p = target - i
if p in d:
return [d[p], k]
else:
d[i] = k