首页 > web前端 > js教程 > 正文

二指针算法解释

Susan Sarandon
发布: 2024-10-07 20:20:30
原创
688 人浏览过

Two pointers algorithm explained

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

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

  • 左/右 该算法的中心概念是有两个整数变量,它们将从字符串或数组的两侧移动。通常,人们称之为左和右。左边将从 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 < right) { // when pointers meet, finish loop
        const sum = arr[left] + arr[right];

        if (sum === target) {
            return [arr[left], arr[right]];  // Return the pair if we find the target sum
        } else if (sum < target) {
            left++;  // Move left pointer to the right if sum is less than target
        } else {
            right--;  // Move right pointer to the left if sum is greater than target
        }
    }

    return null;  // Return null if no such pair exists
}

const arr = [1, 2, 3, 4, 6];
const target = 6;

findPair(arr, target);  // Output: [2, 4]


登录后复制

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


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

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

    let slow = head;
    let fast = head;

    while (fast && 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 -> 2 -> 3 -> 4 -> 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)


登录后复制

以上是二指针算法解释的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!