【每日一题】LeetCode 138. 随机链表的复制 TypeScript
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。
返回复制链表的头节点。
用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
val:一个表示Node.val的整数。random_index:随机指针指向的节点索引(范围从0到n-1);如果不指向任何节点,则为null。
你的代码 只 接受原链表的头节点 head 作为传入参数。
示例 1:

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]] 输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:

输入:head = [[1,1],[2,1]] 输出:[[1,1],[2,1]]
示例 3:

输入:head = [[3,null],[3,0],[3,null]] 输出:[[3,null],[3,0],[3,null]]
首先,来个工作版:
function copyRandomList(head: _Node | null): _Node | null {
return structuredClone(head)
};
开个玩笑,算法版:
整体思路:
1.第一先建立映射,哈希表=>键值对,Map和对象,这题用Map,因为键是非字符串;
建立new Map(旧节点,新链表节点)
”类似于抄写族谱,有甲、乙、丙人名,你先写了人名,但还不知道关系网;”
2.查映射
旧节点的next指向链表的任一的节点
新节点的next也要指向链表的任一节点,和旧节点一样。那么
旧节点有没有next?有,指向 【旧节点的next =链表里的其中一个节点】
新节点就查【旧节点的next =链表里的其中一个节点】一一找到那个节点并指向它
“类似抄写完人名,就画关系图,谁是谁的女儿、祖母、母亲”
有人有疑惑:为什么要分两步?
因为如果走一步复制一步,random指向不确定,可能是未来节点、可能是过去节点,需要更复杂的处理。
/**
* Definition for _Node.
* class _Node {
* val: number
* next: _Node | null
* random: _Node | null
*
* constructor(val?: number, next?: _Node, random?: _Node) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* this.random = (random===undefined ? null : random)
* }
* }
*/
function copyRandomList(head: _Node | null): _Node | null {
if(head===null) return null
const MapNode = new Map<_Node,_Node>()
let cur = head
while(cur){
MapNode.set(cur,new _Node(cur.val))
cur = cur.next
}
cur = head
while(cur){
const node = MapNode.get(cur)
node.next = cur.next?MapNode.get(cur.next):null
node.random = cur.random?MapNode.get(cur.random):null
cur = cur.next
}
return MapNode.get(head)
};
注释版:
/**
* Definition for _Node.
* class _Node {
* val: number
* next: _Node | null
* random: _Node | null
*
* constructor(val?: number, next?: _Node, random?: _Node) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* this.random = (random===undefined ? null : random)
* }
* }
*/
function copyRandomList(head: _Node | null): _Node | null {
//边界条件,删了感觉没影响
if(head===null) return null
//初始化新映射表(哈希表)
const MapNode = new Map<_Node,_Node>()
//指针,初始指向链表的头节点
let cur = head
//遍历
while(cur){
//建立映射关系(旧节点,只有旧节点val的链表)
MapNode.set(cur,new _Node(cur.val))
cur = cur.next
}
//指针又从头开始遍历,查关系
cur = head
while(cur){
//取出新节点的当前节点
const node = MapNode.get(cur)
//新节点的next= 旧节点next指向的节点 > 哈希表里对应的节点
node.next = cur.next?MapNode.get(cur.next):null
//同上
node.random = cur.random?MapNode.get(cur.random):null
cur = cur.next
}
//题干需要返回头节点的链表
return MapNode.get(head)
};
共勉
更多推荐
所有评论(0)