当前位置:网站首页>LeetCode-138-复制带随机指针的链表
LeetCode-138-复制带随机指针的链表
2022-07-26 18:06:00 【z754916067】
题目

思路
- 没啥思路,复制链表好复制,但是random节点位置不好记录,就算记录下来的话每次都要遍历,如果正好所有节点都指向最后一个节点的话那就是O(n^2)的时间复杂度了。
- 有想过题解的解法,但是当时想的是哈希存储链表节点值,但是节点值会重复,于是就卡住了,原来还可以直接存节点,用递归解决…学到了。
代码
//构建哈希表 用来对应原节点和现节点
Map<Node,Node> cacheNode = new HashMap<Node,Node>();
public Node copyRandomList(Node head) {
//此为递归的结束点
if(head==null) return null;
if(!cacheNode.containsKey(head)){
//如果哈希表里的key未包含head 即现节点还没有创建
//以head创建一个新node
Node headNew = new Node(head.val);
cacheNode.put(head,headNew);
head.next = copyRandomList(head.next); //递归时默认已经完成 即已经copy出其next节点
head.random = copyRandomList(head.random);//原理同上
}
//如果已经包含了的话,返回新节点即可
return cacheNode.get(head);
}
边栏推荐
- I'm cool, so I'm here
- LeetCode简单题之第一个出现两次的字母
- Sentinel 隔离与降级
- 工赋开发者社区 | 定了!就在7月30日!
- Gongfu developer community is settled! On July 30!
- Briefly describe the 11 core functional modules of MES system
- MySQL - 函数及约束命令
- MySQL - multi table query and case explanation
- VPC nat (Sant, nant) experiment
- [postgraduate entrance examination vocabulary training camp] day 13 - reliance, expert, subject, unconscious, photograph, exaggeration, counter act
猜你喜欢

【考研词汇训练营】Day 13 —— reliance,expert,subject,unconscious,photograph,exaggeration,counteract

Tensor Rt的int8量化原理

Brand new! Uncover the promotion route of Ali P5 Engineer ~p8 architect

微软默默给 curl 捐赠一万美元,半年后才通知

Likeshop takeout order system is open source, 100% open source, no encryption

Excellent JSON processing tool

NFT digital collection system development: fellow uncle first promoted the blessing series digital collection, which will be sold out immediately

Support proxy direct connection to Oracle database, jumpserver fortress v2.24.0 release

2022茶艺师(中级)考试题模拟考试题库及答案

Gongfu developer community is settled! On July 30!
随机推荐
MongoDB stats统计集合占用空间大小
简述MES系统的11大核心功能模块
手机申请公募reits账户安全吗?
MySQL - 函数及约束命令
MES系统的选择需重点考虑哪些方面?
JS uses readLine to realize terminal input data
当前占位,之后再写
ZbxTable 2.0 重磅发布!6大主要优化功能!
2022 chemical automation control instrument test question simulation test platform operation
2022 mobile crane driver test questions simulation test platform operation
Redis学习笔记-2.客户端的使用
工赋开发者社区 | 定了!就在7月30日!
SD NAND与eMMC优劣势对比
从6月25日考试之后,看新考纲如何复习PMP
Unity 农场 2 —— 种植系统
LeetCode笔记:Weekly Contest 303
LeetCode简单题之数组能形成多少数对
Sentinel isolation and degradation
[interview question] 1384- share 44 JS problems. Half right is a master
Advanced template (runner's notes)