二指针算法解释

原创
ithorizon 5个月前 (10-19) 阅读数 45 #Javascript

我想解释一个简单而有效的技巧,你可以在面试中处理数组、字符串、链表等时使用它。这也将提高你对这些数据结构的基础知识。

让我们从理论开始。该算法有两个常见用例:

  • 左/右 该算法的中心概念是有两个整数变量,它们将从字符串或数组的两侧移动。通常,人们称之为左和右。左边将从 0 索引移动到长度 — 1,右边则相反。

  • 慢/快指针以相同方向运行,例如从开始到结束,但一个指针比另一个指针运行得更快。在这种情况下,人们通常称变量为慢速和快速。

算法是基本的,理解它们的最好方法是研究一些例子。

首先,我们来看一个左右指针的情况。这是我们可以使用该算法解决的问题的基本示例。目标很明确:我们想要找到一对总和等于给定数字的对。
蛮力方法会产生嵌套循环,但通过面试的几率很低。
更好的方法是使用两个指针算法并在一个循环中找到它以具有 o(n) 复杂度而不是 o(n²)


const findpair = (arr, target) => {
    let left = 0;                 // start with two pointers left from start, right, from the end
    let right = arr.length - 1;

    while (left 

<p>让我们切换到指针具有不同速度的方法。这是一个常见的问题,你可以在面试中遇到。您需要找到给定链接列表的中间位置。<br>
蛮力方法并不像前面的例子那么糟糕,但面试官期望有更好的方法。<br>
使用两个指针算法,您将以 o(n) 复杂度解决此问题,而如果您使用两个顺序循环,则暴力方法将需要 o(2n)。</p>

<pre class="brush:php;toolbar:false">

class ListNode {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}

const findMiddle = (head) =&gt; {
    if (!head) return null;

    let slow = head;
    let fast = head;

    while (fast &amp;&amp; fast.next) {
        slow = slow.next;           // Move slow pointer one step
        fast = fast.next.next;      // Move fast pointer two steps
    }

    return slow;  // Slow pointer will be at the middle
}

// Creating a linked list 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5
const head = new ListNode(1);
const node2 = new ListNode(2);
const node3 = new ListNode(3);
const node4 = new ListNode(4);
const node5 = new ListNode(5);

head.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;

findMiddle(head).value);  // Output: 3 (middle node)


以上就是二指针算法解释的详细内容,更多请关注IT视界其它相关文章!



热门