【LeetCode】Copy List with Random Pointer
2024-08-28 10:55:49
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.
思路:第一遍正常复制链表,同一时候用哈希表保存链表中原始节点和新节点的相应关系,第二遍遍历链表的时候,再复制随机域。
这是一种典型的空间换时间的做法,n个节点,须要大小为O(n)的哈希表,同一时候时间复杂度能够减少到O(n)。
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return head;
}
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode res = null;
RandomListNode taiListNode = null;
RandomListNode cur = head;
while (cur != null) {
if (res == null) {
res = new RandomListNode(cur.label);
res.next = res.random = null;
taiListNode = res;
map.put(head, res);
}
else{
taiListNode.next = new RandomListNode(cur.label);
taiListNode = taiListNode.next;
map.put(cur, taiListNode); }
cur = cur.next;
}
taiListNode.next = null;
cur = head;
taiListNode = res;
while (cur != null) {
taiListNode.random = (RandomListNode)map.get((RandomListNode)cur.random);
cur = cur.next;
taiListNode = taiListNode.next;
}
return res;
}
}
最新文章
- 从零开始编写自己的C#框架(19)——Web层后端权限模块
- java代码解压zip文件
- 使用ABP时报错“UPDATE 语句与 FOREIGN KEY SAME TABLE 约束";FK_dbo.AbpUsers_dbo.AbpUsers_LastModifierUserId";冲突”的解决办法
- 【转】SpringTest框架JUnit单元测试用例获取ApplicationContext实例的方法
- IOS 入门开发教程
- 杭电1241 Oil Deposits
- 使用 JavaScript
- web安全之token
- [Irving]DateTime格式处理大全
- 关于FPGA异步时钟采样--结绳法的点点滴滴
- LeetCode_3 sum closet
- linux查看用户登录信息-w命令
- C#区域截图&mdash;&mdash;调用API截图
- jq常用事件(on,blur,focus,change),js/jq等待图片(页面)加载完毕事件,js读取文件
- Linux 的umask详解
- C++11-->单生产者,单消费者问题
- docker镜像的常用操作
- SpringBoot里使用RMI进行远程方法调用
- 用scp命令来通过ssh传输文件,ssh推送.py程序到CentOS7服务器端出现lost connection错误
- 8.17 一个博客demo