[LeetCode] 138. 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.
Example 1:
Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1} Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.
Note:
- You must return the copy of the given head as a reference to the cloned list.
这道链表的深度拷贝题的难点就在于如何处理随机指针的问题,由于每一个节点都有一个随机指针,这个指针可以为空,也可以指向链表的任意一个节点,如果在每生成一个新节点给其随机指针赋值时,都要去遍历原链表的话,OJ 上肯定会超时,所以可以考虑用 HashMap 来缩短查找时间,第一遍遍历生成所有新节点时同时建立一个原节点和新节点的 HashMap,第二遍给随机指针赋值时,查找时间是常数级。代码如下:
解法一:
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
Node *res = new Node(head->val, nullptr, nullptr);
Node *node = res, *cur = head->next;
unordered_map<Node*, Node*> m;
m[head] = res;
while (cur) {
Node *t = new Node(cur->val, nullptr, nullptr);
node->next = t;
m[cur] = t;
node = node->next;
cur = cur->next;
}
node = res; cur = head;
while (cur) {
node->random = m[cur->random];
node = node->next;
cur = cur->next;
}
return res;
}
};
我们可以使用递归的解法,写起来相当的简洁,还是需要一个 HashMap 来建立原链表结点和拷贝链表结点之间的映射。在递归函数中,首先判空,若为空,则返回空指针。然后就是去 HashMap 中查找是否已经在拷贝链表中存在了该结点,是的话直接返回。否则新建一个拷贝结点 res,然后建立原结点和该拷贝结点之间的映射,然后就是要给拷贝结点的 next 和 random 指针赋值了,直接分别调用递归函数即可,参见代码如下:
解法二:
class Solution {
public:
Node* copyRandomList(Node* head) {
unordered_map<Node*, Node*> m;
return helper(head, m);
}
Node* helper(Node* node, unordered_map<Node*, Node*>& m) {
if (!node) return nullptr;
if (m.count(node)) return m[node];
Node *res = new Node(node->val, nullptr, nullptr);
m[node] = res;
res->next = helper(node->next, m);
res->random = helper(node->random, m);
return res;
}
};
当然,如果使用 HashMap 占用额外的空间,如果这道题限制了空间的话,就要考虑别的方法。下面这个方法很巧妙,可以分为以下三个步骤:
1. 在原链表的每个节点后面拷贝出一个新的节点。
2. 依次给新的节点的随机指针赋值,而且这个赋值非常容易 cur->next->random = cur->random->next。
3. 断开链表可得到深度拷贝后的新链表。
举个例子来说吧,比如原链表是 1(2) -> 2(3) -> 3(1),括号中是其 random 指针指向的结点,那么这个解法是首先比遍历一遍原链表,在每个结点后拷贝一个同样的结点,但是拷贝结点的 random 指针仍为空,则原链表变为 1(2) -> 1(null) -> 2(3) -> 2(null) -> 3(1) -> 3(null)。然后第二次遍历,是将拷贝结点的 random 指针赋上正确的值,则原链表变为 1(2) -> 1(2) -> 2(3) -> 2(3) -> 3(1) -> 3(1),注意赋值语句为:
cur->next->random = cur->random->next;
这里的 cur 是原链表中结点,cur->next 则为拷贝链表的结点,cur->next->random 则为拷贝链表的 random 指针。cur->random 为原链表结点的 random 指针指向的结点,因为其指向的还是原链表的结点,所以我们要再加个 next,才能指向拷贝链表的结点。最后再遍历一次,就是要把原链表和拷贝链表断开即可,参见代码如下:
解法二:
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
Node *cur = head;
while (cur) {
Node *t = new Node(cur->val, nullptr, nullptr);
t->next = cur->next;
cur->next = t;
cur = t->next;
}
cur = head;
while (cur) {
if (cur->random) cur->next->random = cur->random->next;
cur = cur->next->next;
}
cur = head;
Node *res = head->next;
while (cur) {
Node *t = cur->next;
cur->next = t->next;
if (t->next) t->next = t->next->next;
cur = cur->next;
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/138
参考资料:
类似题目:
https://leetcode.com/problems/copy-list-with-random-pointer/
https://leetcode.com/problems/copy-list-with-random-pointer/discuss/43488/Java-O(n)-solution
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 138. Copy List with Random Pointer 拷贝带有随机指针的链表的更多相关文章
- [LeetCode] 138. Copy List with Random Pointer 拷贝带随机指针的链表
A linked list is given such that each node contains an additional random pointer which could point t ...
- [leetcode]138. Copy List with Random Pointer复制带有随机指针的链表
public RandomListNode copyRandomList(RandomListNode head) { /* 深复制,就是不能只是复制原链表变量,而是做一个和原来链表一模一样的新链表, ...
- [LeetCode] Copy List with Random Pointer 拷贝带有随机指针的链表
A linked list is given such that each node contains an additional random pointer which could point t ...
- [Leetcode] Copy list with random pointer 对带有任意指针的链表深度拷贝
A linked list is given such that each node contains an additional random pointer which could point t ...
- 力扣——Copy List with Random Pointer(复制带随机指针的链表) python实现
题目描述: 中文: 给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点. 要求返回这个链表的深拷贝. 示例: 输入:{"$id":" ...
- 133. Clone Graph 138. Copy List with Random Pointer 拷贝图和链表
133. Clone Graph Clone an undirected graph. Each node in the graph contains a label and a list of it ...
- Java for LeetCode 138 Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point t ...
- leetcode 138. Copy List with Random Pointer ----- java
A linked list is given such that each node contains an additional random pointer which could point t ...
- leetcode 138. Copy List with Random Pointer复杂链表的复制
python代码如下: # Definition for singly-linked list with a random pointer. # class RandomListNode(object ...
随机推荐
- Vue.js 源码分析(三十二) 总结
第一次写博客,坚持了一个多月时间,Vue源码分析基本分析完了,回过头也看也漏了一些地方,比如双向绑定里的观察者模式,也可以说是订阅者模式,也就是Vue里的Dep.Watcher等这些函数的作用,网上搜 ...
- 阿里云 .NET SDK Roa 和 Rpc 风格签名
阿里云 .NET SDK Roa 和 Rpc 风格的签名 Demo,适用于自己不想用其提供的SDK,想用自己组装 Roa 和 Rpc 的签名方式. Roa 和 Rpc 的签名方式主要有以下几个不同点: ...
- C# 中如何深度复制某一个类型(备注:可能有 N 个类型需要复制)的对象?
如题,针对某一个特定的类型,深度复制,没有那么难,最起码可以手动赋值,但如果要针对 N 多类型深度复制,最简单的方法,是把这个对象序列化成 XML.JSON 或其它可以序列化的载体,然后再将这个载体反 ...
- Logstash:Data转换,分析,提取,丰富及核心操作
Logstash:Data转换,分析,提取,丰富及核心操作 Logstash plugins Logstash是一个非常容易进行扩张的框架.它可以对各种的数据进行分析处理.这依赖于目前提供的超过200 ...
- 百度编辑器上传视频报Http请求错误,.net实现方式
在使用百度编辑器上传视频的时候遇到一个很奇怪的问题,当视频大小在20M以下的时候,上传正常.当大于20M时,一直报Http请求错误. 处理步骤: 1.修改编辑器配置信息,如图所示,改成你想要的大小 2 ...
- C 储存类与运算符
储存类 参考链接:https://www.runoob.com/cprogramming/c-storage-classes.html 存储类定义 C 程序中变量/函数的范围(可见性)和生命周期 au ...
- VMware与 Device/Credential Guard 不兼容,解决办法及心得
以下为心路历程,想要直接解决可以直接拉到最后看后续 百度要你取消Hyper-V功能,但我要用docker,以及一些相关的帖子都无效的情况下 https://blog.csdn.net/u0136677 ...
- JDK1.8新特性——Stream API
JDK1.8新特性——Stream API 摘要:本文主要学习了JDK1.8的新特性中有关Stream API的使用. 部分内容来自以下博客: https://blog.csdn.net/icarus ...
- dga model train and test code
# _*_coding:UTF-8_*_ import operator import tldextract import random import pickle import os import ...
- SDL2学习(一): 显示一张图片
SDL是一个跨平台的多媒体库,它通过OpenGL和2D视频帧缓冲,提供了针对音频.视频.键盘.鼠标.控制杆及3D硬件的低级别的访问接口.这里使用较新的SDL2库. 1. 配置SDL开发环境 1.1 下 ...