返回学习页
知识点指南

Two Pointers

Two pointers use two moving positions to avoid checking every pair or every window from scratch.

什么时候使用

读题时可以留意这些信号。

  • The data is sorted or can be scanned with a moving window.
  • You are looking for pairs, ranges, or longest/shortest windows.
  • Moving one boundary has a predictable effect on the condition.

常见错误

提交前可以检查这些小陷阱。

  • Moving the wrong pointer.
  • Forgetting to update the maintained sum/count.
  • Using two pointers when the data has no monotonic behaviour.

怎么写成代码

把知识点翻译成变量、循环、判断和更新。

  • Set left and right to starting positions.
  • Move right to include more data or move left to remove data.
  • Maintain the current sum/count/condition as pointers move.
  • Update the answer whenever the current window is valid.

在 Block 题里长什么样

答题时通常会看到这些步骤被拆成代码块。

  1. 1Read and optionally sort data.
  2. 2Initialise left/right pointers and current state.
  3. 3Loop while pointers are in range.
  4. 4Move one pointer based on the condition.
  5. 5Update current state.
  6. 6Update answer.

题目里怎么出现

读题时先找这些信号,再决定答案区应该选哪些 blocks。

  • The task asks about a window, pair, or range inside an ordered sequence.
  • Checking all pairs would be too slow.
  • Increasing or decreasing a pointer predictably changes the condition.

Sliding window with sum

一个小型模板,展示代码和 blocks 的对应关系。

C++

int left = 0, sum = 0;
for (int right = 0; right < N; right++) {
    sum += values[right];
    while (sum > limit) {
        sum -= values[left];
        left++;
    }
}

Python

left = 0
sum_value = 0
for right in range(N):
    sum_value += values[right]
    while sum_value > limit:
        sum_value -= values[left]
        left += 1

对应 block 顺序

  1. 1Initialise left and current state.
  2. 2Move right through the array.
  3. 3Add the right value.
  4. 4While condition is invalid, remove left value.
  5. 5Move left.
  6. 6Update answer for valid window.

相关题目

用题库中的相关题目练习这个知识点。

2 道题

建议先练这道题

可以先从 Pairing Cards 开始,再回到这里复盘知识点信号。

打开题目