-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyRandomList.py
More file actions
51 lines (43 loc) · 1.34 KB
/
copyRandomList.py
File metadata and controls
51 lines (43 loc) · 1.34 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
"""
# Definition for a Node.
class Node:
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution:
def __init__(self):
self.visited = {}
def copyRandomList(self, head: 'Node') -> 'Node':
"""
#Approach1 Map
m = {}
curr = res = Node(None, None, None)
while head:
if head in m.keys():
tmp = m[head]
else:
tmp = Node(head.val, None, None)
m[head] = tmp
curr.next = tmp
curr = curr.next
if head.random:
if head.random in m.keys():
random = m[head.random]
else:
random = Node(head.random.val, None, None)
m[head.random] = random
curr.random = random
head = head.next
return res.next
"""
#Approach2 Recursive
if not head: return head
if head in self.visited.keys():
return self.visited[head]
node = Node(head.val, None, None)
self.visited[head] = node
node.next = self.copyRandomList(head.next)
node.random = self.copyRandomList(head.random)
return node