給定一個整數(shù)數(shù)組 nums 和一個目標值 target,請你在該數(shù)組中找出和為目標值的那 兩個 整數(shù),并返回他們的數(shù)組下標。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,你不能重復(fù)利用這個數(shù)組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
使用python 解法 :
暴力解法:
class Solution(object):
def twoSum(self, nums, target):
result = []
t1 = time.time()
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
result.append(i)
result.append(j)
print(time.time() - t1)
return result
數(shù)值比較少的時候沒有問題,當(dāng)數(shù)值過多的時候,會出現(xiàn)超時
字典解法:
class Solution(object):
def twoSum(self, nums, target):
size = 0
d = {}
while size < len(nums):
#先把數(shù)組存到字典里面
if not nums[size] in d:#key不在字典里,進行賦值
d[nums[size]] = size
if target - nums[size] in d:# nums[size] 和 target - nums[size]都在字典里,即存在和為他人個體/的兩個數(shù)
# 這里key 有可能指向同一個數(shù)(即 target - nums[size] = nums[size]時,他其實只有一個數(shù))
if d[target - nums[size]] < d[nums[size]]:
# d的值從小到大輸出
result = [d[target - nums[size]], d[nums[size]]]
return resul
# 注意size = size + 1是和最外層的if平級的
size = size + 1
這種解法是保證數(shù)組沒有相同的數(shù)值,如果有相同的數(shù)值就會輸出錯誤,不過解法的思想是正確的。
第二種字典解法:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = dict()
for index,value in enumerate(nums):
sub = target - value
if sub in dic:
return [dic[sub],index]
else:
dic[value] = index
其實是用了enmumerate ( ) 方法
Python enumerate() 函數(shù)
描述
enumerate() 函數(shù)用于將一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串)組合為一個索引序列,同時列出數(shù)據(jù)和數(shù)據(jù)下標,一般用在 for 循環(huán)當(dāng)中。
Python 2.3. 以上版本可用,2.6 添加 start 參數(shù)。
語法
以下是 enumerate() 方法的語法:
enumerate(sequence, [start=0])
參數(shù)
sequence -- 一個序列、迭代器或其他支持迭代對象。
start -- 下標起始位置。
返回值
返回 enumerate(枚舉) 對象。
實例
以下展示了使用 enumerate() 方法的實例:
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']>>> list(enumerate(seasons))[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]>>> list(enumerate(seasons, start=1)) # 下標從 1 開始[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
普通的 for 循環(huán)
>>>i = 0>>> seq = ['one', 'two', 'three']>>> for element in seq: ... print i, seq[i]... i +=1... 0 one1 two2 three
for 循環(huán)使用 enumerate
>>>seq = ['one', 'two', 'three']>>> for i, element in enumerate(seq): ... print i, element... 0 one1 two2 three