标签:get for sum 给定一个整数数组 pytho 两数之和 none enumerate enum
给定一个整数数组 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
标签:get for sum 给定一个整数数组 pytho 两数之和 none enumerate enum
原文地址:https://www.cnblogs.com/zyyhxbs/p/12771769.html