[leetcode]python3 演算法攻略-兩數之和
阿新 • • 發佈:2019-02-17
給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。
方案一:利用字典,儲存檢查過的元素及其索引。
def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d = {} for i in range(len(nums)): t = target - nums[i] if t in d: return [d[t], i] d[nums[i]] = i
方案二:不使用字典,但是效率上低了許多。
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
t = target - nums[i]
if t in nums and nums.index(t) != i:
return [i, nums.index(t)]