脚本宝典收集整理的这篇文章主要介绍了LeetCode 刷题 小本本 Two Sum,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 给定一个list和target,找到list中加起来等于target的索引,不能重复使用值。
def twoSum1(self, nums, target):
"""
:tyPE nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in nums:
sub = target - i
nums_copy = nums.copy()
nums_copy.remove(i)
if sub in (nums_copy):
index_i = nums.index(i)
index_j = nums.index(sub,index_i+1)
break
return [index_i, index_j]
遇到的问题:
def twoSum(self, nums, target):
hashmap = {@H_802_126@}
for i in range(len(nums)):
complement = target - nums[i]
if complement in hashmap:
return [i, hashmap[complement]]
hashmap[nums[i]] = i
更好的处理了不能重复使用相同值的问题:
class Solution:
def twoSum(self, nums, target):
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h:
h[num] = i
else:
return [h[n], i]
这个地方把list转成了dict,然后也用了hashmap的思路。
以上是脚本宝典为你收集整理的LeetCode 刷题 小本本 Two Sum全部内容,希望文章能够帮你解决LeetCode 刷题 小本本 Two Sum所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。