> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/algorithm-techniques/two-pointers.md).

# 双指针与滑动窗口

### 相向双指针

两个指针从两端向中间移动，常用于有序数组求和、反转、回文判断。

```cpp
// 有序数组中找两数之和等于 target
int l = 0, r = n - 1;
while (l < r) {
    int s = a[l] + a[r];
    if (s == target) break;
    else if (s < target) l++;
    else r--;
}
```

### 同向双指针 / 滑动窗口

维护区间 \[l, r]，右指针扩张、左指针收缩，解决“连续子数组”问题。

```cpp
// 和 >= target 的最短连续子数组长度
int l = 0, sum = 0, ans = INF;
for (int r = 0; r < n; r++) {
    sum += a[r];
    while (sum >= target) {
        ans = min(ans, r - l + 1);
        sum -= a[l++];
    }
}
```

### 适用条件

数组有序或窗口具有**单调性**，一般把 O(n²) 降到 O(n)。

### 应用

两数/三数之和、最短/最长子数组、字符串匹配、去重。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/algorithm-techniques/two-pointers.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
