PHP前端开发

二指针算法解释

百变鹏仔 3天前 #JavaScript
文章标签 指针

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

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

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

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

const findpair = (arr, target) =&gt; {    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; 5const 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)