-
Notifications
You must be signed in to change notification settings - Fork 187
/
138. Copy List with Random Pointer.java
82 lines (74 loc) · 2.43 KB
/
138. Copy List with Random Pointer.java
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
138. Copy List with Random Pointer
Solution 1: hashmap + 2 iteration
第一遍deep copy每个node并存hashmap,第二遍根据hashmap来deep copy random指针(注意条件:cur.random != null)
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode dummy = new RandomListNode(0), cur = dummy;
Map<RandomListNode, RandomListNode> map = new HashMap<>();
while (head != null) {
RandomListNode newNode = new RandomListNode(head.label);
map.put(head, newNode);
newNode.random = head.random;
cur.next = newNode;
cur = cur.next;
head = head.next;
}
cur = dummy.next;
while (cur != null) {
if (cur.random != null)
cur.random = map.get(cur.random);
cur = cur.next;
}
return dummy.next;
}
Solution 2: hashmap + 1 iteration
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode dummy = new RandomListNode(0), cur = dummy;
Map<RandomListNode, RandomListNode> map = new HashMap<>();
while (head != null) {
RandomListNode newNode = null;
if (map.containsKey(head))
newNode = map.get(head);
else {
newNode = new RandomListNode(head.label);
map.put(head, newNode);
}
if (head.random != null) // ATTENTION
if (map.containsKey(head.random))
newNode.random = map.get(head.random);
else {
newNode.random = new RandomListNode(head.random.label);
map.put(head.random, newNode.random);
}
cur.next = newNode;
cur = cur.next;
head = head.next;
}
return dummy.next;
}
Solution 3: copy -> random -> split
Space: O(1)
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
RandomListNode cur = head;
while (cur != null) {
RandomListNode newNode = new RandomListNode(cur.label);
newNode.next = cur.next;
cur.next = newNode;
cur = cur.next.next;
}
cur = head;
while (cur != null) {
if (cur.random != null)
cur.next.random = cur.random.next;
cur = cur.next.next;
}
cur = head;
RandomListNode newHead = head.next;
while (cur != null) {
RandomListNode newNode = cur.next;
cur.next = newNode.next;
cur = cur.next;
if (cur != null) newNode.next = cur.next;
}
return newHead;
}