实现说明
真正干活的是函数 pair_with_sum,其余都是接线。
while left < right 反复执行,循环体之外没有别的重复。
使用要点
- 调用方只需要
pair_with_sum——其余都是内部实现。
常见问题
不安装任何包也能运行吗?
可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件在加载时定义 pair_with_sum。
入口签名:def pair_with_sum(values, target)
代码示例
# Two pointers on a sorted array: start at both ends and walk inward.
# If the pair sum is too small only a bigger left value can help, and
# if it is too big only a smaller right value can — so one linear pass
# either finds the pair or proves none exists.
def pair_with_sum(values, target):
left, right = 0, len(values) - 1
while left < right:
current = values[left] + values[right]
if current == target:
return values[left], values[right]
if current < target:
left += 1
else:
right -= 1
return None
ordered = [2, 3, 5, 8, 11, 15]
print(pair_with_sum(ordered, 13))
print(pair_with_sum(ordered, 10))
print(pair_with_sum(ordered, 40))