1:題目描述 Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would ...
1:題目描述
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
給出一組數據及一個目標數字,找出這組數據中數字之和為目標數字的兩個數字,返回他們的索引位置
2:解題困惑
初次使用python完成題目,對於面向對象還不能充分理解,所以借鑒了網上的例子
3:解題思路
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
NUM={} #設置一個字典,將輸入的數字及對應下標存儲到裡面
for index,num in enumerate(nums): #使用for以及enumerate()函數遍歷nums數組
if target-num in NUM: #如果target-num 在NUM字典中
return (NUM[target-num],index) #返回target-num,以及num的索引位置
NUM[num]=index #向字典中存儲num以及下標