一腌歉、題目
給定一個整數(shù)數(shù)組 nums 和一個目標(biāo)值 target秕磷,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個 整數(shù),并返回他們的數(shù)組下標(biāo)采蚀。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是承二,你不能重復(fù)利用這個數(shù)組中同樣的元素榆鼠。
難度:簡單
鏈接:兩數(shù)字和#
二、示例
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
三亥鸠、解答
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i, m in enumerate(nums):
dict[m] = i
for i, m in enumerate(nums):
j = dict.get(target - m)
if j is not None and i != j:
return [i, j]