-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
34 lines (31 loc) · 889 Bytes
/
Copy pathSolution.java
File metadata and controls
34 lines (31 loc) · 889 Bytes
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
import java.util.HashMap;
class Solution {
//Time Complexity: O(n)
//Space Complexity: O(n)
public Node copyRandomList(Node head) {
if (head == null) return null;
Node res = new Node(head.val);
//old -> new
HashMap<Node, Node> hashMap = new HashMap<>();
Node node = res;
Node cur = head.next;
hashMap.put(head, res);
//Create new nodes and maps from old to new.
while (cur != null){
Node temp = new Node(cur.val);
node.next = temp;
hashMap.put(cur, temp);
node = node.next;
cur = cur.next;
}
//deal with random
node = res;
cur = head;
while (cur != null){
node.random = hashMap.get(cur.random);
node = node.next;
cur = cur.next;
}
return res;
}
}