-
Notifications
You must be signed in to change notification settings - Fork 0
/
0138.py
52 lines (48 loc) · 1.5 KB
/
0138.py
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
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class CopyNode:
def __init__(self, x = 0, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def copyRandomList1(self, head: 'Node') -> 'Node':
if not head:
return head
dic = collections.defaultdict(CopyNode)
q = collections.deque([head])
while q:
cur = q.popleft()
dic[cur].val = cur.val
if cur.random:
dic[cur.random].val = cur.random.val
dic[cur].random = dic[cur.random]
if cur.next:
dic[cur.next].val = cur.next.val
dic[cur].next = dic[cur.next]
q.append(cur.next)
else:
break
return dic[head]
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return head
dic = collections.defaultdict(Node)
cur = head
while cur:
dic[cur] = Node(cur.val, None, None)
cur = cur.next
cur = head
while cur:
nxt = dic.get(cur.next, None)
rdm = dic.get(cur.random, None)
dic[cur].next = nxt
dic[cur].random = rdm
cur = cur.next
return dic[head]