← 中文资源

简体中文版本

双指针在有序数组内相向而行

有序数组找目标和用双指针:和太小移左指针、太大移右指针,两指针相向而行相遇即停,一次线性扫描定位数对或证明不存在,无需嵌套循环。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

(2, 11)
(2, 8)
None

实现说明

真正干活的是函数 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))