python输入10个数、 找出其中距离最近的两个数_Python编程题10--找出和为N的两个数...

题目

给定一个列表和一个目标值N,列表中元素均为不重复的整数。请从该列表中找出和为目标值N的两个整数,然后只返回其对应的下标组合。

注意:列表中同一个元素不能使用两遍。

例如:

给定列表 [2, 7, 11, 15],目标值N为 18,因为 7 + 11 = 18,那么返回的结果为 (1, 2)

给定列表 [2, 7, 11, 6, 13],目标值N为 13,因为 2 + 11 = 13,7 + 6 = 13,那么符合条件的结果为 (0, 2)、(1, 3)

实现思路1

利用 多层循环 来实现

通过两层遍历,第一层遍历的元素下标为 i ,第二层遍历的元素下标为 j

i与j 不能为下标相同的同一元素,再比较 i与j 的和是否等于目标值target

判断下标组合是否在结果列表中,如果不在则添加到结果列表中

代码实现

def find_two_number(nums, target):

res = []

for i in range(len(nums)):

for j in range(len(nums)):

if i != j and nums[i] + nums[j] == target and (i, j) not in res and (j, i) not in res:

res.append((i, j))

return res

nums = [1, 2, 4, 3, 6, 5]

target = 7

res = find_two_number(nums, target)

print("列表中两数之和为 {} 的下标组合为:{}".format(target, res))

实现思路2

利用 列表 来实现,列表的 index() 方法仅返回指定值首次出现的位置

通过遍历,得到每次遍历时的元素下标 i ,对应的元素为 cur_num

利用目标值 target 减去 cur_num ,得到另一个数 other_num

判断另一个数 other_num 是否存在于当前列表中,如果存在则表示列表中有符合条件的两个数,即可把对应的下标组合添加到结果列表中

代码实现

def find_two_number(nums, target):

res = []

for i in range(len(nums)):

cur_num, other_num = nums[i], target - nums[i]

if other_num in nums[i+1:]:

res.append((i, nums.index(other_num)))

return res

nums = [1, 2, 4, 3, 6, 5]

target = 7

res = find_two_number(nums, target)

print("列表中两数之和为 {} 的下标组合为:{}".format(target, res))

实现思路3

利用 字典 来实现

通过遍历,得到每次遍历时的元素下标 i ,对应的元素为 cur_num

利用目标值 target 减去 cur_num ,得到另一个数 other_num

判断另一个数 other_num 是否存在于当前字典 temp_dict 的键中,如果不存在就把当前数 cur_num 及其对应列表中的下标 i 作为键值对,存储到字典中

如果字典 temp_dict 的键中存在另一个数 other_num,则表示列表中有符合条件的两个数,即可把对应的下标组合添加到结果列表中

代码实现

def find_two_number(nums, target):

res = []

temp_dict = {}

for i in range(len(nums)):

cur_num, other_num = nums[i], target - nums[i]

if other_num not in temp_dict:

temp_dict[cur_num] = i

else:

res.append((temp_dict[other_num], i))

return res

nums = [1, 2, 4, 3, 6, 5]

target = 7

res = find_two_number(nums, target)

print("列表中两数之和为 {} 的下标组合为:{}".format(target, res))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值