【leetcode】(初级算法-数组)两数之和【Python】
- 两数之和
- 说明
- 示例1
- 方法一:遍历,耗时很长
- 方法二:字典
两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
说明
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例1
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
方法一:遍历,耗时很长
# 两数之和
Nums,Target = [2,7,11,15],9
# 方法一:遍历,耗时很长
def twoSum(nums, target):
res = []
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j] == target:
res.append(i)
res.append(j)
break
return res
print(twoSum(Nums,Target))
方法二:字典
# 方法二:字典
def twoSum(nums, target):
# 创建一个空字典
d = {}
for i in range(len(nums)):
j = target-nums[i]
# 字典中是否存在nums[i]
if nums[i] in d:
return [d[nums[i]],i]
else:
d[j]=i
print(twoSum(Nums,Target))
最后
以上就是爱笑发带最近收集整理的关于【leetcode】(初级算法-数组)两数之和【Python】两数之和的全部内容,更多相关【leetcode】(初级算法-数组)两数之和【Python】两数之和内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复