📅  最后修改于: 2023-12-03 14:55:30.373000             🧑  作者: Mango
在编程中,经常需要在一个数组中寻找满足特定条件的一对数。这种情况可谓是多种多样,例如:
接下来,我们将以一个具体的例子来讲解如何在 Python 中找到满足给定条件的一对数。
假设有一个数组 [2, 7, 11, 15]
,现在要在这个数组中寻找一对数,它们的和等于 9。
def two_sum(nums, target):
seen = {}
for index, num in enumerate(nums):
other = target - num
if other in seen:
return [seen[other], index]
seen[num] = index
return []
nums = [2, 7, 11, 15]
target = 9
print(two_sum(nums, target))
以上代码使用哈希表记录已经遍历过的数及其下标,然后对于当前遍历到的数 num
,计算另一个数 other
,使得 num + other == target
。如果 other
已经出现在哈希表中,那么就找到了一对满足条件的数。具体而言,以下是算法的主要步骤:
seen
,用来记录已经遍历过的数及其下标。for index, num in enumerate(nums):
表示对于数组 nums
中的每个元素 num
,同时返回它在数组中的下标 index
,并执行缩进的代码块。other
,使得 num + other == target
。具体而言,other = target - num
。other
已经在 seen
中出现过,那么就找到了一对满足条件的数,返回它们的下标(在这里,为什么返回下标而不是返回数值,是为了方便输出结果):return [seen[other], index]
。seen
中记录当前数 num
及其下标 index
,以便后续遍历时使用:seen[num] = index
。[]
。在上述例子中,输出结果为 [0, 1]
,表示数组中下标为 0
和 1
的两个数字 2
和 7
相加得到了 9
。根据上面的代码,我们也可以轻易地修改 target 的值或 nums 的值,以在不同的场景下寻找满足特定条件的一对数。