-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
57 lines (45 loc) · 1.07 KB
/
solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* @lc app=leetcode id=138 lang=javascript
*
* [138] Copy List with Random Pointer
*/
// @lc code=start
/**
* // Definition for a Node.
* function Node(val, next, random) {
* this.val = val;
* this.next = next;
* this.random = random;
* };
*/
type MaybeNode = Node | null;
class Node {
constructor(
public val: number = 0,
public next: MaybeNode = null,
public random: MaybeNode = null,
) {}
}
/**
* @param {Node} head
* @return {Node}
*/
const copyRandomList = (head: MaybeNode): MaybeNode => {
// * ['52 ms', '90.58 %', '35.7 MB', '100 %']
if (head === null) return null;
const map = new Map<Node, Node>();
let cur: MaybeNode = head;
const mirrorOf = (node: Node): Node => {
if (!map.has(node)) map.set(node, new Node(node.val));
return map.get(node)!;
};
while (cur) {
const newNode = mirrorOf(cur);
if (cur.next) newNode.next = mirrorOf(cur.next);
if (cur.random) newNode.random = mirrorOf(cur.random);
cur = cur.next;
}
return map.get(head)!;
};
// @lc code=end
export { Node, copyRandomList };