-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path05CopyListWithRandomPointer.java
More file actions
46 lines (38 loc) · 1.4 KB
/
05CopyListWithRandomPointer.java
File metadata and controls
46 lines (38 loc) · 1.4 KB
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
// Time Complexity: O(n)
// Space Complexity: O(n)
class Solution {
public Node copyRandomList(Node head) {
if (head == null) return null;
// Map original node to its clone
Map<Node, Node> originalToClone = new HashMap<>();
Node res = new Node(0);
Node dummy = res;
// Idea: Clone the list linearly and avoid duplicate cloning by using a map
while (head != null) {
// Clone next node, if in map use the existing clone
Node nextClone;
if (originalToClone.containsKey(head)) {
nextClone = originalToClone.get(head);
} else {
nextClone = new Node(head.val);
originalToClone.put(head, nextClone);
}
dummy.next = nextClone;
// Clone random node, if in map use the existing clone
Node randomClone = null;
if (head.random != null) {
if (originalToClone.containsKey(head.random)) {
randomClone = originalToClone.get(head.random);
} else {
randomClone = new Node(head.random.val);
originalToClone.put(head.random, randomClone);
}
}
dummy.next.random = randomClone;
// Iterate
dummy = nextClone;
head = head.next;
}
return res.next;
}
}