240
生活,简单就好!

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))

更多Python编程题,等你来挑战:Python编程题汇总(持续更新中……)

posted @ 2020-10-05 12:49  wintest  阅读(1159)  评论(2编辑  收藏  举报