Python两数之和
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
相关推荐
EdwardSiCong 2020-11-23
yungpheng 2020-10-19
jipengx 2020-11-12
橄榄 2020-11-03
lyqdanang 2020-11-02
wservices 2020-10-30
onepiecedn 2020-10-29
数据人 2020-10-26
dfphoto 2020-10-16
hackerlpy 2020-09-07
tianyayi 2020-08-16
Dullonjiang 2020-08-15
fengling 2020-08-15
wordmhg 2020-08-06
guotiaotiao 2020-08-06
zhangsyi 2020-07-28
千锋 2020-07-27
ahnjwj 2020-07-28