Python编程题10--找出和为N的两个数

2020-10-05  本文已影响0人  wintests

题目

给定一个列表和一个目标值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

代码实现

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

代码实现

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

代码实现

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编程题汇总(持续更新中……)

上一篇下一篇

猜你喜欢

热点阅读