Problem: 138. 随机链表的复制
思路 & 解题方法
哈希。
复杂度
时间复杂度:
O ( n ) O(n) O(n)
空间复杂度:
O ( n ) O(n) O(n)
Code
"""
# 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 Solution:
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
cur = head
node1 = ans = Node(0, None, None)
mp = collections.defaultdict(Node)
while cur:
node2 = Node(cur.val, None, None)
node1.next = node2
node1 = node2
mp[cur] = node1
cur = cur.next
cur = head
ans_cur = ans.next
while cur:
if cur.random:
ans_cur.random = mp[cur.random]
ans_cur = ans_cur.next
cur = cur.next
return ans.next