跳转至

05 - 双指针与滑动窗口

1. 适用场景

  • 序列/字符串的连续区间问题
  • 需要在线维护窗口状态
  • 条件具有“可收缩”或“单调”特征

2. 双指针模板

Python
def two_sum_sorted(nums, target):
    l, r = 0, len(nums) - 1
    while l < r:
        s = nums[l] + nums[r]
        if s == target:
            return [l, r]
        if s < target:
            l += 1
        else:
            r -= 1
    return []

3. 滑动窗口模板

Python
from collections import defaultdict

def longest_without_repeat(s: str) -> int:
    cnt = defaultdict(int)
    l = 0
    ans = 0
    for r, ch in enumerate(s):
        cnt[ch] += 1
        while cnt[ch] > 1:
            cnt[s[l]] -= 1
            l += 1
        ans = max(ans, r - l + 1)
    return ans

4. 复杂度要求

  • 双指针:O(n)
  • 滑窗:每个元素最多进出一次,O(n)

5. 训练清单

  • 两数之和 II (有序)
  • 盛最多水的容器
  • 最小覆盖子串
  • 找到字符串中所有异位词