给定一个列表和一个目标值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)
代码实现
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))
代码实现
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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))
代码实现
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))