当前位置:网站首页>复制带随机指针的链表[空间换时间--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
参考文献
边栏推荐
- [LeetCode] 只出现一次的数字【136】
- On binary tree
- I wonder if I can open an account today? In addition, is it safe to open an account online now?
- 网上开户选哪个证券公司?还有,在线开户安全么?
- 手机开户一般哪个证券公司好?另外,手机开户安全么?
- MySQL multi table query
- 深度学习的历史
- AI首席架构师9-胡晓光 《飞桨模型库与行业应用》
- 云和恩墨盖国强,识别它、抓住它,在国产数据库沸腾以前
- 二叉搜索树 230. 二叉搜索树中第K小的元素 1038. 从二叉搜索树到更大和树
猜你喜欢

MySQL functions and constraints

QT learning 01 GUI program principle analysis

云服务器的安全设置常识

Sword finger offer 14- ii Cutting rope II

新钛云服荣膺“2022爱分析 · IT运维厂商全景报告”云管理平台CMP 代表厂商!...
500 error occurred after importing skins folder into solo blog skin

Matplotlib histogram of Matplotlib visualization plt bar()

LC: maximum subarray and

一步步教你在Edge浏览器上安装网风笔记

What is IGMP? What is the difference between IGMP and ICMP?
随机推荐
Golang泛型的巧妙应用,防止变量空指针错误,防止结构体字段空指针错误
This simple little function saves 213 hours for our production research team in half a year
Construction of module 5 of actual combat Battalion
招商证券靠谱吗?开股票账户安全吗?
Why is JSX syntax so popular?
HPE launched ARM CPU general server product
Leetcode (633) -- sum of squares
Divisor
LC:有效的数独 + 旋转图像
【微信小程序】认识小程序项目的基本组成结构
Bee常用配置
Fund valuation, expenses and accounting
Solr basic operation 1
Teach you step by step to install webwind notes on edge browser
What is online account opening? In addition, is it safe to open a mobile account?
6.28日刷题题解
Cacti settings for spin polling
Siemens low code platform connects MySQL through database connector to realize addition, deletion, modification and query
Xutils3 transfer set
【一起上水硕系列】Day 8