双指针

两个常用场景(数组中)

  1. 前后同时,从不同位置出发
    从两端向中间迭代数组。
    一个指针从始端开始,而另一个指针从末端开始。
    值得注意的是,这种技巧经常在排序数组中使用。

比如:反转字符串,数组拆分,两数和(有序数组)

  1. 两个不同步的指针(一个快指针一个慢指针),速度不同
    解决这类问题的关键是确定两个指针的移动策略。

比如: 原地移除元素。最大连续1的个数,长度最小的子数组

Tips

你有时可能需要在使用双指针技巧之前对数组进行排序,也可能需要运用贪心想法来决定你的运动策略

双指针在链表中的应用

双指针技术
删除倒数第n个节点:19,61,143
判断有没有环lc141,lc142
回文链234

链表中双指针模板

// Initialize slow & fast pointers
ListNode slow = head;
ListNode fast = head;
/**
 * Change this condition to fit specific problem.
 * Attention: remember to avoid null-pointer error
 **/
while (slow != null && fast != null && fast.next != null) {
    slow = slow.next;           // move slow pointer one step each time
    fast = fast.next.next;      // move fast pointer two steps each time
    if (slow == fast) {         // change this condition to fit specific problem
        return true;
    }
}
return false;   // change return value to fit specific problem

双指针在滑动窗口

显示 Gitment 评论