【LeetCode】707. 设计链表(中等)——代码随想录算法训练营Day03

题目链接:707. 设计链表

题目描述

你可以选择使用单链表或者双链表,设计并实现自己的链表。

单链表中的节点应该具备两个属性:val 和 next 。val 是当前节点的值,next 是指向下一个节点的指针/引用。

如果是双向链表,则还需要属性 prev 以指示链表中的上一个节点。假设链表中的所有节点下标从 0 开始。

实现 MyLinkedList 类:

  • MyLinkedList() 初始化 MyLinkedList 对象。
  • int get(int index) 获取链表中下标为 index 的节点的值。如果下标无效,则返回 -1 。
  • void addAtHead(int val) 将一个值为 val 的节点插入到链表中第一个元素之前。在插入完成后,新节点会成为链表的第一个节点。
  • void addAtTail(int val) 将一个值为 val 的节点追加到链表中作为链表的最后一个元素。
  • void addAtIndex(int index, int val) 将一个值为 val 的节点插入到链表中下标为 index 的节点之前。如果 index 等于链表的长度,那么该节点会被追加到链表的末尾。如果 index 比长度更大,该节点将 不会插入 到链表中。
  • void deleteAtIndex(int index) 如果下标有效,则删除链表中下标为 index 的节点。

示例:

输入
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
输出
[null, null, null, null, 2, null, 3]

解释
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2);    // 链表变为 1->2->3
myLinkedList.get(1);              // 返回 2
myLinkedList.deleteAtIndex(1);    // 现在,链表变为 1->3
myLinkedList.get(1);              // 返回 3

提示:

0 <= index, val <= 1000
请不要使用内置的 LinkedList 库。
调用 get、addAtHead、addAtTail、addAtIndex 和 deleteAtIndex 的次数不超过 2000 。

文章讲解:代码随想录

视频讲解:帮你把链表操作学个通透!LeetCode:707.设计链表_哔哩哔哩_bilibili

题解1:虚拟头节点

思路:虚拟头节点的思想起始就是带头节点的链表,真正存储数据的头节点是虚拟头节点的下一个节点。使用虚拟头节点可以将对头节点和中间节点的处理方法统一,简化代码逻辑。

/**
 * 初始化链表
 * @return {void}
*/
var MyLinkedList = function() {
    this.head = { val: 0 }; // 虚拟头节点
    this.size = 0; // 链表长度
};

/** 
 * 获取到第 index 个节点数值,如果 index 是非法数值直接返回-1, 注意 index 是从0开始的,第0个节点就是头结点
 * @param {number} index
 * @return {number}
 */
MyLinkedList.prototype.get = function(index) {
    if (index >= this.size) {
        return -1;
    }

    let cur = this.head.next;
    for (let i = 0; i < index; i++) {
        cur = cur.next;
    }
    return cur.val;
};

/** 
 * 在第 index 个节点之前插入一个新节点
 * 如果 index 为0,那么新插入的节点为链表的新头节点
 * 如果 index 等于链表的长度,则说明是新插入的节点为链表的尾结点
 * @param {number} index 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtIndex = function(index, val) {
    if (index > this.size) {
        return;
    }

    const node = { val }
    let cur = this.head;
    for (let i = 0; i < index; i++) {
        cur = cur.next;
    }
    node.next = cur.next;
    cur.next = node;
    this.size++;
};

/** 
 * 在链表最前面插入一个节点,插入完成后,新插入的节点为链表的新的头结点
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtHead = function(val) {
    this.addAtIndex(0, val);
};

/** 
 * 在链表最后面添加一个节点
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtTail = function(val) {
    this.addAtIndex(this.size, val);
};

/** 
 * 删除第 index 个节点,如果 index 大于等于链表的长度,直接 return,注意 index 是从0开始的
 * @param {number} index
 * @return {void}
 */
MyLinkedList.prototype.deleteAtIndex = function(index) {
    if (index >= this.size) {
        return;
    }

    let cur = this.head;
    for (let i = 0; i < index; i++) {
        cur = cur.next;
    }
    cur.next = cur.next.next;
    this.size--;
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * var obj = new MyLinkedList()
 * var param_1 = obj.get(index)
 * obj.addAtHead(val)
 * obj.addAtTail(val)
 * obj.addAtIndex(index,val)
 * obj.deleteAtIndex(index)
 */

分析:尾部插入节点、根据 index 插入节点、获取节点、删除节点需要遍历单链表,时间复杂度为 O(n),空间复杂度为 O(1)。头部插入节点不需要遍历链表,直接从头指针后插入,时间复杂度为 O(1),空间复杂度为 O(1)。

题解2:双链表

思路:在单链表中,每个节点都有一个后继指针指向它们的后继节点。在单链表的基础上,给每个节点加一个前驱指针指向它们的前驱节点,就成了双向链表。

/**
 * 初始化链表
 * @return {void}
*/
var MyLinkedList = function() {
    this.head = { val: 0 }; // 虚拟头节点
    this.tail = { val: 0 }; // 虚拟尾节点
    this.head.next = this.tail;
    this.tail.pre = this.head;
    this.size = 0; // 链表长度
};

/** 
 * 获取到第 index 个节点数值,如果 index 是非法数值直接返回-1, 注意 index 是从0开始的,第0个节点就是头结点
 * @param {number} index
 * @return {number}
 */
MyLinkedList.prototype.get = function(index) {
    if (index >= this.size) {
        return -1;
    }

    // 比较遍历链表找到 index,是从头节点开始近还是尾节点开始近
    // 目标元素位置为 index,链表总长为 size,最左元素位置为0,最右元素位置为 size - 1
    // 距左:index - 0    距右:(size - 1) - index
    if (index <= this.size - 1 - index) {
        let cur = this.head.next;
        // 目前 cur 指向位置0,向后移动 (index - 0) 步后指向位置 index
        for (let i = 0; i < index; i++) {
            cur = cur.next;
        }
        return cur.val;
    } else {
        let cur = this.tail.pre;
        // 目前 cur 指向 tail 的前驱节点,向前移动 (size - 1 - index) 步后指向位置 index
        for (let i = 0; i < this.size - 1 - index; i++) {
            cur = cur.pre;
        }
        return cur.val;
    }
};

/** 
 * 在第 index 个节点之前插入一个新节点
 * 如果 index 为0,那么新插入的节点为链表的新头节点
 * 如果 index 等于链表的长度,则说明是新插入的节点为链表的尾结点
 * @param {number} index 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtIndex = function(index, val) {
    if (index > this.size) {
        return;
    }

    const node = { val }
    let [pre, next] = [null, null]; // 新节点的前驱指针和后继指针

    // 比较遍历链表找到 index 前插入的节点,是从头节点开始近还是尾节点开始近
    if (index <= this.size - 1 - index) {
        pre = this.head;
        // 目前 pre 指向 head,向后移动 (index - 0) 步后指向插入节点后的位置 index 的前驱节点
        for (let i = 0; i < index; i++) {
            pre = pre.next;
        }
        next = pre.next; // 将 next 指向 pre 的后继节点
    } else {
        next = this.tail;
        // 目前 cur 指向 tail,向前移动 (size - index) 步后指向插入节点后的位置 index 的后继节点
        for (let i = 0; i < this.size - index; i++) {
            next = next.pre;
        }
        pre = next.pre; // 将 pre 指向 next 的前驱节点
    }

    // 在 pre 和 next 之间插入节点
    [node.pre, node.next] = [pre, next];
    pre.next = node;
    next.pre = node;
    this.size++;
};

/** 
 * 在链表最前面插入一个节点,插入完成后,新插入的节点为链表的新的头结点
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtHead = function(val) {
    this.addAtIndex(0, val);
};

/** 
 * 在链表最后面添加一个节点
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtTail = function(val) {
    this.addAtIndex(this.size, val);
};

/** 
 * 删除第 index 个节点,如果 index 大于等于链表的长度,直接 return,注意 index 是从0开始的
 * @param {number} index
 * @return {void}
 */
MyLinkedList.prototype.deleteAtIndex = function(index) {
    if (index >= this.size) {
        return;
    }

    // 比较遍历链表找到 index,是从头节点开始近还是尾节点开始近
    if (index <= this.size - 1 - index) {
        let cur = this.head;
        // 目前 cur 指向 head,向后移动 (index - 0) 步后指向位置 index 的前驱节点
        for (let i = 0; i < index; i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        cur.next.pre = cur; 
    } else {
        let cur = this.tail;
        // 目前 cur 指向 tail,向前移动 (size - 1 - index) 步后指向位置 index 的后继节点
        for (let i = 0; i < this.size - 1 - index; i++) {
            cur = cur.pre;
        }
        cur.pre = cur.pre.pre;
        cur.pre.next = cur;
    }
    this.size--;
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * var obj = new MyLinkedList()
 * var param_1 = obj.get(index)
 * obj.addAtHead(val)
 * obj.addAtTail(val)
 * obj.addAtIndex(index,val)
 * obj.deleteAtIndex(index)
 */

分析:双链表的每个元素对比单链表多了一个前驱节点,在插入、删除操作时可以从两边进行遍历,目标位置距离哪边更近就从哪边遍历。

根据 index 插入节点、获取节点、删除节点需要遍历双链表,时间复杂度为 O(n),空间复杂度为 O(1)。头部插入节点和尾部插入节点不需要遍历链表,直接从头指针后和尾指针前插入,时间复杂度为 O(1),空间复杂度为 O(1)。

收获

熟悉了单链表和双链表的基础构建方法,学会了如何对链表进行插入节点、删除节点、获取节点数据等简单的操作。单链表改进为双链表的过程中,再次体现出边界值判断的重要性,更加提高了我编写代码的能力。

  • 28
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
第二十二天的算法训练营主要涵盖了Leetcode题目中的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串中找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组中的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组中找到长度最小的子数组,使得子数组的和大于等于给定的目标值。这里可以使用滑动窗口的方法来解决问题。使用两个指针来表示滑动窗口的左边界和右边界,通过移动指针来调整滑动窗口的大小,使得滑动窗口中的元素的和满足题目要求。具体实现的代码如下: ```python def minSubArrayLen(self, target: int, nums: List[int]) -> int: left = 0 right = 0 ans = float('inf') total = 0 while right < len(nums): total += nums[right] while total >= target: ans = min(ans, right - left + 1) total -= nums[left] left += 1 right += 1 return ans if ans != float('inf') else 0 ``` 以上就是第二十二天的算法训练营的内容。通过这些题目的练习,可以提升对双指针和滑动窗口等算法的理解和应用能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晴雪月乔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值