当前位置:网站首页>复制带随机指针的链表[空间换时间--hash记录]
复制带随机指针的链表[空间换时间--hash记录]
2022-06-29 23:53:00 【REN_林森】
前言
空间换时间是非常常见的降低时间复杂度做法,而hashMap/hash数组/二进制hash就是常用的方式。
一、复制带随机指针的链表

二、hash记录
package everyday.hash;
import java.util.HashMap;
import java.util.Map;
public class CopyRandomList {
public Node copyRandomList(Node head) {
// 设置dummy节点,把特殊情况head==null,以及头节点问题统一处理了。
Node dummyHead = new Node(1);
dummyHead.next = head;
Node cloneDummyHead = new Node(1);
// 记录原始节点和新生成节点映射。
Map<Node, Node> fx = new HashMap<>();
// 设置好头节点与游走节点。
Node p = dummyHead.next;
Node cur = cloneDummyHead.next;
// 设置next
while (p != null) {
// 生成新节点
Node next = new Node(p.val);
// 记录新旧节点映射,为后面设置random指针做准备。
fx.put(p, next);
// 设置新链表next
cur.next = next;
// 更新cur/p
cur = cur.next;
p = p.next;
}
// 设置random
p = dummyHead.next;
cur = cloneDummyHead.next;
while (p != null) {
// 得到cur节点random指向。
Node random = fx.get(p.random);
// 设置random
cur.random = random;
// 更新cur/p
cur = cur.next;
p = p.next;
}
// 返回克隆好的链表
return cloneDummyHead.next;
}
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
}
总结
1)空间换时间,hashMap/hashSet/hash数组/二进制hash
参考文献
边栏推荐
- 一步步教你在Edge浏览器上安装网风笔记
- FPGA开发(2)——IIC通信
- 云服务器的安全设置常识
- Applet plug-in access, development and precautions
- Xutils3 transfer set
- How to write controller layer code gracefully?
- Fund valuation, expenses and accounting
- AI empowers new retail, the way to win "wisdom" lies in ecological thinking | selected excerpts from digital intelligence night talk live broadcast
- 架构实战营模块5作业
- LC:最大子数组和
猜你喜欢

Jetpack之Room的使用,结合Flow

FPGA开发(1)——串口通信

6.29日刷题题解

Leetcode(76)——最小覆盖子串

Construction of module 5 of actual combat Battalion

打造一个 API 快速开发平台,牛逼!

About mongodb error: connecting to: mongodb://127.0.0.1:27017/?compressors=disabled &gssapiServiceName=mongodb

How to view the CPU cores and threads in win11? Win11 view the tutorial of how many cores and threads the CPU is

matlab习题 —— 程序控制流程练习

數莓派 4怎麼樣?可能的玩法有哪些?
随机推荐
请指教什么是在线开户?另外,手机开户安全么?
6.28日刷题题解
Matplotlib histogram of Matplotlib visualization plt bar()
Analysis of define incdir command in TCL script of Modelsim
Web APIs 环境对象 丨黑马程序员
Andorid source build/envsetup.sh 该知道的细节
[wechat applet] understand the basic composition of the applet project
Machine learning: the concept and application of VC dimension
Sword finger offer 13 Range of motion of robot
6.29日刷题题解
[leetcode] a number that appears only once [136]
我想知道今天还可以开户么?另外想问,现在在线开户安全么?
Solr basic operation 2
Provide effective performance evaluation 
Fund valuation, expenses and accounting
打造一个 API 快速开发平台,牛逼!
深度学习的历史
穿越过后,她说多元宇宙真的存在
【一起上水硕系列】Day 8
LC:有效的数独 + 旋转图像