给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
解答:
1、暴力穷举法:
遍历每个元素 x,并查找是否存在一个值与 target - xtarget−x 相等的目标元素
代码实现:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l=len(nums) #列表长度
for i in range(l):
for j in range(i+1,l):
if nums[i]+nums[j]==target:
return i,j;
2 先创建一个空字典,然后依次把target-nums[x]的值存入字典,存入一个就跟nums[x+1]去比较, 字典中的key为target-nums[x],value为x,也就是nums[x]在nums列表中的索引位置。当字典d中有nums[x+1]时,也就是target - nums[y] = nums[x+1] , y肯定是小于x+1的(因为y是x+1之前循环过的数字) --------------------- 本文来自 linfeng886 的优快云 博客 ,全文地址请点击:https://blog.youkuaiyun.com/linfeng886/article/details/79772348?utm_source=copy
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# 用len()方法取得nums列表长度
n = len(nums)
# 创建一个空字典
d = {}
for x in range(n):
a = target - nums[x]
# 字典d中存在nums[x]时
if nums[x] in d:
return d[nums[x]], x
# 否则往字典增加键/值对
else:
d[a] = x
# 边往字典增加键/值对,边与nums[x]进行对比
本文详细解析了在给定数组中寻找两数之和等于目标值的算法。介绍了两种方法:暴力穷举法和使用字典的高效解法。通过实例展示了如何利用字典快速定位配对元素,提高搜索效率。


被折叠的 条评论
为什么被折叠?



