-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path105_copy_list_with_random_pointer.py
More file actions
92 lines (78 loc) · 1.9 KB
/
105_copy_list_with_random_pointer.py
File metadata and controls
92 lines (78 loc) · 1.9 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
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
83
84
85
86
87
88
89
90
91
92
"""
Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
"""
"""
using hashmap
time: O(2n) => O(n)
space: O(n)
"""
class Solution:
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
N = {}
dummy = tail = RandomListNode(-1)
while head:
node = RandomListNode(head.label)
node.random = head.random
tail.next = node
N[head] = node
tail = tail.next
head = head.next
head = dummy.next
while head:
if head.random:
head.random = N[head.random]
head = head.next
return dummy.next
"""
temply save in n.next
time: O(3n) => O(n)
space: O(1)
example: 1->2->3
copy_next/
|--------->|
1 -> 1' -> 2 -> 2' -> 3 -> 3'
replace_random/
|--------->|
|----+---->| |
1 -> 1' -> 2 -> 2' -> 3 -> 3'
split_list/
|--------->|
1 -> 2 -> 3
1' -> 2' -> 3'
|--------->|
"""
class Solution:
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return
tail = head
node = None
while tail:
node = RandomListNode(tail.label)
node.random = tail.random
node.next = tail.next
tail.next = node
tail = tail.next.next
tail = head
while tail:
if tail.next and tail.random:
tail.next.random = tail.random.next
tail = tail.next.next
node = tail = head.next
while tail and tail.next:
tail.next = tail.next.next
tail = tail.next
return node