問題描述
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個數組中同樣的元素。
Sol 1:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
index=[]
for f_index,i in enumerate(nums):
for s_index,j in enumerate(nums[f_index+1:]):
if i + j ==target:
index.append(f_index)
index.append(f_index + s_index + 1)
return index
方法1是很直接的想法,用兩次循環將每兩個數依次相加,函數可以獲得對應的索引,時間複雜度爲,空間複雜度爲,運行時間爲6692ms,內存佔用爲7.2M。
Sol 2:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
hashmap[num] = index
return None
方法2是比較巧妙的想法了,只用了一次循環,在進行迭代並將元素插入到表中的同時,我們還會回過頭來檢查表中是否已經存在當前元素所對應的目標元素。如果它存在,那我們已經找到了對應解,並立即將其返回。
時間複雜度:O(n), 我們只遍歷了包含有 n 個元素的列表一次。
空間複雜度:O(n), 所需的額外空間取決於哈希表中存儲的元素數量,該表最多需要存儲 n 個元素。
運行時間爲44ms,內存佔用爲7.9M。
結論
方法1:時間複雜度高,空間複雜度稍低
方法2:空間複雜度稍高,時間複雜度很低