Two Pointers

Summary

 两个指针
• 对撞型 (2 sum 类 和 partition 类)
• 前向型 (窗口类, 快慢类)
• 两个数组,两个指针 (并行)
模板
• 2 Sum类模板
• Partition 类模板
• 窗口类模板

1. “对撞型”或“相会型”

Two Sum类题目思路

if (A[i] + A[j] > sum)
    j--;
    do something
else if (A[i] + A[j] < sum)
    i++;
    do something
else
    do something
    i++ or j--

灌水类型题目思路

这一类通过对撞型指针优化算法,根本上其实要证明就是不用扫描多余状态

Partition类模板

Partition 另一种模板

相会型指针题目

  • 2 Sum 类 (通过判断条件优化算法)

    • 3 Sum Closest

    • 4 Sum

    • 3 Sum

    • Two sum II

    • Triangle Count

    • Trapping Rain Water

    • Container With Most Water

  • Partition 类

    • Partition-array

    • Sort Colors

    • Partition Array by Odd and Even

    • Sort Letters by Case

    • Valid Palindrome

    • quick sort\/ quick select\/ nuts bolts problem\/wiggle sort II

2. 前向型或者追击型

窗口类

窗口类指针移动模板

通过两层for循环改进算法 --- 不同于sliding window

快慢类

前向型指针题目

  • 窗口类

    • Remove Nth Node From End of List

    • minimum-size-subarray-sum

    • Minimum Window Substring

    • Longest Substring with At Most K Distinct Characters

    • Longest Substring Without Repeating Characters

    • Longest Repeating Character Replacement

  • 快慢类

    • Find the Middle of Linked L

两个数组两个指针

两个数组各找一个元素, 使得和等于target

  1. 找一种

  2. 找全部种类

From @LeetCode

Two-pointer Technique - Scenario I (相会型)

One of the typical scenarios to use two-pointer technique is you want to:

Iterate the array from two ends to the middle.

So that you can use the two-pointer technique:

One pointer starts from the beginning while the other pointer starts from the end.

This technique is often used in a sorted array.

Two-pointer Technique - Scenario II (快慢型)

two pointers with different steps to solve problems.

Scenario:

One slow-runner and one fast-runner at the same time.

The key to solving this kind of problems is to

Determine the movement strategy for both pointers.

Similar to the previous scenario, you might sometimes need to sort the array before using the two-pointer technique. And you might need a greedy thought to determine your movement strategy.

应用场景

Two Pointer Technique can be used to solve:

Sliding Window Problem

904.Fruit Into Baskets

424.Longest Repeating Character Replacement

Last updated

Was this helpful?