Repository navigation
Expand file tree
/
Copy pathSolution.java
More file actions
56 lines (45 loc) Β· 1.35 KB
/
Copy pathSolution.java
File metadata and controls
56 lines (45 loc) Β· 1.35 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
47
48
49
50
51
52
53
54
55
56
package linkedlist.copyrand;
import java.util.HashMap;
import java.util.Map;
/**
* @see <a href="https://leetcode.com/problems/copy-list-with-random-pointer">Copy List with Random Pointer</a>
*/
public class Solution {
/**
* Solution with a HashMap.
* <p>
* Time complexity: O(n)
* Space complexity: O(n)
*/
Node copyRandomList(Node head) {
Map<Node, Node> originalToCopy = new HashMap<>();
Node current = head;
while (current != null) {
originalToCopy.put(current, new Node(current.val));
current = current.next;
}
current = head;
while (current != null) {
Node copy = originalToCopy.get(current);
copy.next = originalToCopy.get(current.next);
copy.random = originalToCopy.get(current.random);
current = current.next;
}
return originalToCopy.get(head);
}
// TODO: a more clever implementation exits without using a HashMap
// See: https://leetcode.com/problems/copy-list-with-random-pointer/discuss
Node copyRandomListNoMap(Node head) {
return null;
}
static class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
}