【面試題57 和爲s的兩個數字】
面試題57:和爲s的兩個數字:輸入一個遞增排序的數組和一個數字s,在數組中查找兩個數,使得它們的和正好是s。如果有多對數字的和等於s,則輸出任意一對即可。
思路一:哈希表。遍歷數組一遍,邊遍歷邊向回查找,假設當前值是 m
,那麼向前查找 target-m
,如果找到了則直接返回,否則就將當前值 m
登記在哈希表中。
時間複雜度:
空間複雜度:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for m in nums:
n = dict.get(target-m, 0) # 查找鍵target-m,若找不到默認返回0
if n != 0:
return [target-m, m]
dict[m] = 1
思路二:雙指針(對撞指針)。由於題目已經說了是遞增數組,說明數組內部有序,那麼可以用雙指針分別指向數組頭和尾,計算和,若和大於目標值,則讓尾向前一步,若和小於目標值,則讓頭向後一步,若和等於目標值,直接返回。
時間複雜度:,最壞情況下,兩個指針會收縮到數組中央
空間複雜度:,只需要維護兩個指針
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
i, j = 0, len(nums)-1
while i < j:
s = nums[i] + nums[j]
if s > target: j -= 1
elif s < target: i += 1
else: return [nums[i], nums[j]]