​LeetCode刷题实战138:复制带随机指针的链表

该博客旨在提升大家的算法能力,后续每天会从LeetCode选一道算法题讲解。此次讲解的是复制带随机指针的链表问题,给出了题目描述和样例,解题可利用HashMap,先遍历生成所有节点存入其中,再遍历更新节点的next和random指针,还提及有其他解法。

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 复制带随机指针的链表,我们先来看题面:

https://leetcode-cn.com/problems/copy-list-with-random-pointer/

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

The Linked List is represented in the input/output as a list of n nodes. Each      node is represented as a pair of [val, random_index] where:

val: an integer representing Node.val

random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.

 

题意

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的 深拷贝。 

我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:

val:一个表示 Node.val 的整数。

random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。

样例

解题

这题可以利用 HashMap 来实现。

遍历第一遍链表,我们不考虑链表之间的相互关系,仅仅生成所有节点,然后把它存到 HashMap 中,val 作为 key,Node 作为 value。

遍历第二遍链表,将之前生成的节点取出来,更新它们的 next 和 random 指针。

public Node copyRandomList(Node head) {
    if (head == null) {
        return null;
    }
    HashMap<Node, Node> map = new HashMap<>();
    Node h = head;
    while (h != null) {
        Node t = new Node(h.val); 
        map.put(h, t);
        h = h.next;
    }
    h = head;
    while (h != null) {
        if (h.next != null) {
            map.get(h).next = map.get(h.next);
        }
        if (h.random != null) {
            map.get(h).random = map.get(h.random);
        }
        h = h.next;
    }
    return map.get(head);
}

本题还有很多其他的解法,大家都多思考一下 。

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。

上期推文:

LeetCode1-120题汇总,希望对你有点帮助!

LeetCode刷题实战121:买卖股票的最佳时机

LeetCode刷题实战122:买卖股票的最佳时机 II

LeetCode刷题实战123:买卖股票的最佳时机 III

LeetCode刷题实战124:二叉树中的最大路径和

LeetCode刷题实战125:验证回文串

LeetCode刷题实战126:单词接龙 II

LeetCode刷题实战127:单词接龙

LeetCode刷题实战128:最长连续序列

LeetCode刷题实战129:求根到叶子节点数字之和

LeetCode刷题实战130:被围绕的区域

LeetCode刷题实战131:分割回文串

LeetCode刷题实战132:分割回文串 II

LeetCode刷题实战133:克隆图

LeetCode刷题实战134:加油站

LeetCode刷题实战135:分发糖果

LeetCode刷题实战136:只出现一次的数字

LeetCode刷题实战137:只出现一次的数字 II

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

编程IT圈

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

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

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

打赏作者

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

抵扣说明:

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

余额充值