算法—复杂链表的复制

LeetCode 中等题,题目链接:https://leetcode.cn/problems/fu-za-lian-biao-de-fu-zhi-lcof/description/

题目

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null

Tips:

  1. Node.random为空或者指向链表中的节点
  2. 节点数目不超过 1000;

Node 类定义如下:

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}

示例1:

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]

输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]

示例2:

输入:head = [[1,1],[2,1]]

输出:[[1,1],[2,1]]

示例3:

输入:head = [[3,null],[3,0],[3,null]]

输出:[[3,null],[3,0],[3,null]]

思路

这道题有两个思路:

  1. 使用 Map 容器key 存原链表节点,value 存新节点,原链表的 next 节点是 Map 中对应的 value 节点,原链表的 random 节点是 Map 中对应的 value 节点或者空。
  2. 拼接 + 拆分,原链表的每个节点下一个指针指向的是新节点(old -> new -> old -> new -> null),新节点的 random 节点是前一个节点的 random 节点的下一个节点。

方法一:使用 Map

步骤

  1. 存新老节点到 Map
  2. 使用 Map 复制节点的 next 指针和 random 指针

代码

class Solution {
    public Node copyRandomList(Node head) {
        Map<Node, Node> map = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = cur.random == null ? null : map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
}

复杂度分析

时间复杂度: O ( N ) O(N) O(N)

空间复杂度: O ( N ) O(N) O(N)

方法二:拼接+拆分

  1. 先遍历一遍,组合出新的链表
  2. 再次遍历,复制随机值
  3. 最后一次遍历,拆分链表

代码

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) {
            return head;
        }
        // 组合链表
        Node cur = head;
        Node next = null;
        while (cur != null) {
            next = cur.next; 
            cur.next = new Node(cur.val);
            cur.next.next = next;
            cur = next;
        }
        // 复制随机值
        cur = head;
        while (cur != null) {
            next = cur.next;
            next.random = cur.random == null ? null : cur.random.next;
            cur = next.next;
        }
        // 拆分链表
        Node res = head.next;
        cur = head;
        while (cur != null) {
            next = cur.next;
            cur.next = next.next;
            cur = cur.next;
            next.next = cur == null ? null : cur.next;
        }
        return res;
    }
}

复杂度分析

时间复杂度: O ( N ) O(N) O(N)

空间复杂度: O ( 1 ) O(1) O(1)

总结

这是一道 LeetCode 中等题,难点在于如何用更少的空间完成代码,只要思路正确,剩下的就是处理边界条件了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员@wen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值