Python兩數之和
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
思路一:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
i = index_2 = None
for i in range(0, len(nums)):
if (target - nums[i]) in nums and ((target - nums[i]) != nums[i] or nums.count(nums[i]) > 1):
index_2 = nums.index(target - nums[i], i + 1)
break
return [i, index_2] if index_2 else []
思路二:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
i = index_2 = None
for i in range(0, len(nums)):
if (target - nums[i]) in nums[i + 1:] and ((target - nums[i]) != nums[i] or nums.count(nums[i]) > 1):
index_2 = nums.index(target - nums[i], i + 1)
break
return [i, index_2] if index_2 else []
思路三:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash_map = {}
for i, t in enumerate(nums):
if target - t in hash_map:
return [hash_map[target - t], i]
hash_map[t] = i